File size: 26,788 Bytes
9d2d895
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * RouteExplorer β€” full-screen modal for the worldwide Route Explorer.
 *
 * Sprint 3 wires the Current / Alternatives / Land tabs to the
 * `get-route-explorer-lane` RPC, renders results in the left rail and tab
 * panels, and drives map overlays via `MapContainer` primitives.
 */

import { CountryPicker } from './CountryPicker';
import { Hs2Picker } from './Hs2Picker';
import { CargoTypeDropdown } from './CargoTypeDropdown';
import { KeyboardHelp } from './KeyboardHelp';
import { LeftRail } from './components/LeftRail';
import { CurrentRouteTab } from './tabs/CurrentRouteTab';
import { AlternativesTab } from './tabs/AlternativesTab';
import { LandTab } from './tabs/LandTab';
import { CountryImpactTab } from './tabs/CountryImpactTab';
import { inferCargoFromHs2, type ExplorerCargo } from './RouteExplorer.utils';
import COUNTRY_PORT_CLUSTERS from '../../../scripts/shared/country-port-clusters.json';
import {
  parseExplorerUrl,
  serializeExplorerUrl,
  writeExplorerUrl,
  DEFAULT_EXPLORER_STATE,
  type ExplorerUrlState,
  type ExplorerTab,
} from './url-state';
import type { GetRouteExplorerLaneResponse, GetRouteImpactResponse, BypassCorridorOption } from '@/generated/server/worldmonitor/supply_chain/v1/service_server';
import { fetchRouteExplorerLane, fetchRouteImpact } from '@/services/supply-chain';
import { hasPremiumAccess } from '@/services/panel-gating';
import { getAuthState } from '@/services/auth-state';
import { trackGateHit, track, type UmamiEvent } from '@/services/analytics';

import { TRADE_ROUTES } from '@/config/trade-routes';
import { setTrustedHtml, trustedHtml } from '@/utils/dom-utils';


const TAB_LABELS: Record<ExplorerTab, string> = { 1: 'Current', 2: 'Alternatives', 3: 'Land', 4: 'Impact' };
const FETCH_DEBOUNCE_MS = 250;

const CARGO_TO_ROUTE_CATEGORY: Record<string, string> = {
  container: 'container',
  tanker: 'energy',
  bulk: 'bulk',
  roro: 'container',
};

const ROUTE_CATEGORY_MAP = new Map(TRADE_ROUTES.map((r) => [r.id, r.category]));

interface MapRef {
  highlightRoute(routeIds: string[]): void;
  clearHighlightedRoute(): void;
  setBypassRoutes(corridors: Array<{ fromPort: [number, number]; toPort: [number, number] }>): void;
  clearBypassRoutes(): void;
  zoomToRoutes(routeIds: string[]): void;
}

interface TestHook {
  lastHighlightedRouteIds?: string[];
  lastBypassRoutes?: Array<{ fromPort: [number, number]; toPort: [number, number] }>;
  lastClearHighlight?: number;
  lastClearBypass?: number;
}

declare global {
  interface Window {
    __routeExplorerTestHook?: TestHook;
  }
}

export class RouteExplorer {
  private root: HTMLDivElement | null = null;
  private state: ExplorerUrlState;
  private fromPicker!: CountryPicker;
  private toPicker!: CountryPicker;
  private hs2Picker!: Hs2Picker;
  private cargoDropdown!: CargoTypeDropdown;
  private tabStrip!: HTMLDivElement;
  private contentEl!: HTMLDivElement;
  private leftRail!: LeftRail;
  private currentTab!: CurrentRouteTab;
  private alternativesTab!: AlternativesTab;
  private landTab!: LandTab;
  private impactTab!: CountryImpactTab;
  public impactData: GetRouteImpactResponse | null = null;
  private cargoManual = false;
  private isOpen = false;
  private previousFocus: HTMLElement | null = null;
  private helpOverlay: KeyboardHelp | null = null;
  private mapRef: MapRef | null = null;
  private generationId = 0;
  private debounceTimer: ReturnType<typeof setTimeout> | null = null;
  private laneData: GetRouteExplorerLaneResponse | null = null;
  public isLoading = false;
  private displayMode: 'idle' | 'loading' | 'data' | 'error' | 'gate' = 'idle';
  private openedAt = 0;
  private queryCount = 0;
  private gateHitTracked = false;

  constructor() {
    this.state = { ...DEFAULT_EXPLORER_STATE };
    this.installTestHook();
  }

  public setMap(map: MapRef | null): void {
    this.mapRef = map;
  }

  public open(source: 'cmdk' | 'url' | 'icon' = 'cmdk'): void {
    if (this.isOpen) {
      this.fromPicker?.focusInput();
      return;
    }
    this.state = this.readInitialState();
    this.laneData = null;
    this.displayMode = 'idle';
    this.previousFocus = (document.activeElement as HTMLElement) ?? null;
    this.root = this.buildRoot();
    const mapSection = document.getElementById('mapSection');
    if (mapSection) {
      mapSection.insertAdjacentElement('beforebegin', this.root);
    } else {
      document.body.append(this.root);
    }
    this.isOpen = true;
    this.openedAt = Date.now();
    this.queryCount = 0;
    if (!this.gateHitTracked && this.tier === 'free') {
      trackGateHit('route-explorer');
      this.gateHitTracked = true;
    }
    this.trackEvent('route-explorer:opened', { source });
    document.addEventListener('keydown', this.handleGlobalKeydown, { capture: true });
    this.focusInitial();
    if (this.isQueryComplete()) this.scheduleFetch();
  }

  public close(): void {
    if (!this.isOpen || !this.root) return;
    this.generationId++;
    if (this.debounceTimer) { clearTimeout(this.debounceTimer); this.debounceTimer = null; }
    document.removeEventListener('keydown', this.handleGlobalKeydown, { capture: true });
    this.helpOverlay?.element.remove();
    this.helpOverlay = null;
    this.trackEvent('route-explorer:closed', {
      durationSec: Math.round((Date.now() - this.openedAt) / 1000),
      queryCount: this.queryCount,
    });
    this.clearMapState();
    this.root.remove();
    this.root = null;
    this.isOpen = false;
    this.laneData = null;
    if (this.previousFocus && document.body.contains(this.previousFocus)) {
      this.previousFocus.focus();
    }
    this.previousFocus = null;
  }

  public isOpenNow(): boolean {
    return this.isOpen;
  }

  // ─── State helpers ──────────────────────────────────────────────────────

  private readInitialState(): ExplorerUrlState {
    if (typeof window === 'undefined') return { ...DEFAULT_EXPLORER_STATE };
    return parseExplorerUrl(window.location.search);
  }

  private writeStateToUrl(): void {
    writeExplorerUrl(this.state);
  }

  private isQueryComplete(): boolean {
    return Boolean(this.state.fromIso2 && this.state.toIso2 && this.state.hs2);
  }

  private getEffectiveCargo(): string {
    return this.state.cargo ?? inferCargoFromHs2(this.state.hs2);
  }

  // ─── Data fetching ────────────────────────────────────────────────────

  private scheduleFetch(): void {
    if (this.debounceTimer) clearTimeout(this.debounceTimer);
    this.debounceTimer = setTimeout(() => {
      this.debounceTimer = null;
      this.queryCount++;
      this.trackEvent('route-explorer:query', {
        from: this.state.fromIso2 ?? '',
        to: this.state.toIso2 ?? '',
        hs2: this.state.hs2 ?? '',
        cargo: this.getEffectiveCargo(),
      });
      void this.fetchLane();
    }, FETCH_DEBOUNCE_MS);
  }

  private resetLaneState(mode?: 'loading' | 'error' | 'gate'): void {
    this.laneData = null;
    this.impactData = null;
    this.clearMapState();
    this.leftRail?.updateLane(null, mode);
    this.leftRail?.updateResilience(null);
    this.currentTab?.update(null);
    this.alternativesTab?.update(null);
    this.landTab?.update(null);
    this.impactTab?.update(null);
  }

  private async fetchLane(): Promise<void> {
    if (!this.isQueryComplete()) return;
    if (!hasPremiumAccess(getAuthState())) {
      this.generationId++;
      this.displayMode = 'gate';
      this.resetLaneState('gate');
      this.renderFreeGate();
      this.applyPublicRouteHighlight();
      return;
    }

    const gen = ++this.generationId;
    this.displayMode = 'loading';
    this.resetLaneState('loading');
    this.isLoading = true;
    this.showLoading();

    try {
      const data = await fetchRouteExplorerLane({
        fromIso2: this.state.fromIso2!,
        toIso2: this.state.toIso2!,
        hs2: this.state.hs2!,
        cargoType: this.getEffectiveCargo(),
      });
      if (gen !== this.generationId) return;
      this.laneData = data;
      this.displayMode = 'data';
      this.applyData(data);
      if (!data.noModeledLane) {
        this.applyMapState(data);
      }
      void this.fetchResilience(data.toIso2);
      void this.fetchImpact(data.fromIso2, data.toIso2, data.hs2);
    } catch {
      if (gen !== this.generationId) return;
      this.displayMode = 'error';
      this.resetLaneState('error');
      this.showError();
    } finally {
      if (gen === this.generationId) this.isLoading = false;
    }
  }

  private async fetchResilience(iso2: string): Promise<void> {
    const gen = this.generationId;
    try {
      const { getResilienceScore } = await import('@/services/resilience');
      const res = await getResilienceScore(iso2);
      if (!this.isOpen || gen !== this.generationId) return;
      this.leftRail.updateResilience(res);
      this.impactTab.updateResilience(res);
    } catch {
      if (gen !== this.generationId) return;
      this.leftRail.updateResilience(null);
      this.impactTab.updateResilience(null);
    }
  }

  private async fetchImpact(fromIso2: string, toIso2: string, hs2: string): Promise<void> {
    const gen = this.generationId;
    try {
      const data = await fetchRouteImpact({ fromIso2, toIso2, hs2 });
      if (!this.isOpen || gen !== this.generationId) return;
      this.impactData = data;
      this.impactTab.update(data);
      this.leftRail.updateDependencyFlags(data.dependencyFlags);
      if (data.comtradeSource === 'bilateral-hs4') {
        this.trackEvent('route-explorer:impact-viewed', { toIso2, hs2 });
      }
      if (this.state.tab === 4) this.showActiveTab();
    } catch {
      if (gen !== this.generationId) return;
      this.impactTab.update(null);
    }
  }

  // ─── Map integration ──────────────────────────────────────────────────

  private applyMapState(data: GetRouteExplorerLaneResponse): void {
    if (!this.mapRef || data.noModeledLane || !data.primaryRouteId) return;
    this.mapRef.zoomToRoutes([data.primaryRouteId]);
    this.mapRef.highlightRoute([data.primaryRouteId]);
    if (typeof window !== 'undefined' && window.__routeExplorerTestHook) {
      window.__routeExplorerTestHook.lastHighlightedRouteIds = [data.primaryRouteId];
    }
  }

  private handleBypassSelect(option: BypassCorridorOption): void {
    if (!this.mapRef || !option.fromPort || !option.toPort) return;
    this.trackEvent('route-explorer:alternative-selected', { corridorId: option.id });
    const corridors = [{ fromPort: [option.fromPort.lon, option.fromPort.lat] as [number, number], toPort: [option.toPort.lon, option.toPort.lat] as [number, number] }];
    this.mapRef.setBypassRoutes(corridors);
    if (typeof window !== 'undefined' && window.__routeExplorerTestHook) {
      window.__routeExplorerTestHook.lastBypassRoutes = corridors;
    }
  }

  private clearMapState(): void {
    if (!this.mapRef) return;
    this.mapRef.clearHighlightedRoute();
    this.mapRef.clearBypassRoutes();
    if (typeof window !== 'undefined' && window.__routeExplorerTestHook) {
      window.__routeExplorerTestHook.lastClearHighlight = Date.now();
      window.__routeExplorerTestHook.lastClearBypass = Date.now();
    }
  }

  // ─── Rendering ────────────────────────────────────────────────────────

  private applyData(data: GetRouteExplorerLaneResponse): void {
    this.leftRail.element.classList.remove('re-leftrail--blurred');
    this.leftRail.element.removeAttribute('aria-hidden');
    this.leftRail.updateLane(data);
    this.currentTab.update(data);
    this.alternativesTab.update(data);
    this.landTab.update(data);
    this.showActiveTab();
  }

  private showLoading(): void {
    if (this.contentEl) {
      setTrustedHtml(this.contentEl, trustedHtml('<div class="re-content__loading">Loading lane data\u2026</div>', "legacy direct innerHTML migration"));
    }
  }

  private showError(): void {
    if (this.contentEl) {
      setTrustedHtml(this.contentEl, trustedHtml('<div class="re-content__error">Failed to load lane data. Try again.</div>', "legacy direct innerHTML migration"));
    }
  }

  private renderFreeGate(): void {
    this.leftRail?.element.classList.add('re-leftrail--blurred');
    this.leftRail?.element.setAttribute('aria-hidden', 'true');
    if (this.contentEl) {
      setTrustedHtml(this.contentEl, trustedHtml('<div class="re-content__gate">' +
        '<h3>Unlock route intelligence</h3>' +
        '<ul><li>Current route with chokepoint risk</li><li>Ranked bypass alternatives</li><li>Overland corridor options</li></ul>' +
        '<button class="re-content__upgrade" type="button">Upgrade to PRO</button>' +
        '</div>', "legacy direct innerHTML migration"));
      const btn = this.contentEl.querySelector<HTMLButtonElement>('.re-content__upgrade');
      btn?.addEventListener('click', () => {
        this.trackEvent('route-explorer:free-cta-click', {
          from: this.state.fromIso2 ?? '',
          to: this.state.toIso2 ?? '',
          hs2: this.state.hs2 ?? '',
        });
        void import('@/services/checkout')
          .then((m) => m.startCheckout('pro_monthly'))
          .catch(() => window.open('https://worldmonitor.app/pro', '_blank', 'noopener,noreferrer'));
      }, { once: true });
    }
  }

  private applyPublicRouteHighlight(): void {
    if (!this.mapRef || !this.state.fromIso2 || !this.state.toIso2) return;
    const clusters = COUNTRY_PORT_CLUSTERS as unknown as Record<string, { nearestRouteIds: string[] }>;
    const fromRoutes = new Set(clusters[this.state.fromIso2]?.nearestRouteIds ?? []);
    const toRoutes = new Set(clusters[this.state.toIso2]?.nearestRouteIds ?? []);
    const shared = [...fromRoutes].filter((r) => toRoutes.has(r));
    if (shared.length === 0) return;
    const cargoCategory = CARGO_TO_ROUTE_CATEGORY[this.getEffectiveCargo()] ?? 'container';
    const ranked = [...shared].sort((a, b) => {
      const catA = ROUTE_CATEGORY_MAP.get(a) ?? '';
      const catB = ROUTE_CATEGORY_MAP.get(b) ?? '';
      return (catA === cargoCategory ? 0 : 1) - (catB === cargoCategory ? 0 : 1);
    });
    const routeId = ranked[0] ?? '';
    if (routeId) {
      this.mapRef.highlightRoute([routeId]);
      this.mapRef.zoomToRoutes([routeId]);
    }
  }

  private showActiveTab(): void {
    if (!this.contentEl) return;
    if (this.displayMode === 'loading' || this.displayMode === 'error' || this.displayMode === 'gate') {
      return;
    }
    setTrustedHtml(this.contentEl, trustedHtml('', "legacy direct innerHTML migration"));
    switch (this.state.tab) {
      case 1: this.contentEl.append(this.currentTab.element); break;
      case 2: this.contentEl.append(this.alternativesTab.element); break;
      case 3: this.contentEl.append(this.landTab.element); break;
      case 4: this.contentEl.append(this.impactTab.element); break;
    }
  }

  // ─── DOM construction ──────────────────────────────────────────────────

  private buildRoot(): HTMLDivElement {
    const root = document.createElement('div');
    root.className = 're-modal';
    root.setAttribute('role', 'complementary');
    root.setAttribute('aria-label', 'Route Explorer \u2014 plan a shipment');

    const surface = document.createElement('div');
    surface.className = 're-modal__surface';
    surface.append(this.buildQueryBar(), this.buildTabStrip(), this.buildBody());

    root.append(surface);
    return root;
  }

  private buildQueryBar(): HTMLDivElement {
    const bar = document.createElement('div');
    bar.className = 're-querybar';

    const back = document.createElement('button');
    back.type = 'button';
    back.className = 're-querybar__back';
    back.textContent = '\u2190 Back';
    back.setAttribute('aria-label', 'Close Route Explorer');
    back.addEventListener('click', () => this.close());

    this.fromPicker = new CountryPicker({
      placeholder: 'From country',
      initialIso2: this.state.fromIso2,
      onCommit: (iso2) => this.handleFromCommit(iso2),
      onCancel: () => this.blurActiveInput(),
    });

    const arrow = document.createElement('span');
    arrow.className = 're-querybar__arrow';
    arrow.textContent = '\u2192';
    arrow.setAttribute('aria-hidden', 'true');

    this.toPicker = new CountryPicker({
      placeholder: 'To country',
      initialIso2: this.state.toIso2,
      onCommit: (iso2) => this.handleToCommit(iso2),
      onCancel: () => this.blurActiveInput(),
    });

    this.hs2Picker = new Hs2Picker({
      placeholder: 'Pick a product',
      initialHs2: this.state.hs2,
      onCommit: (hs2) => this.handleHs2Commit(hs2),
      onCancel: () => this.blurActiveInput(),
    });

    const initialCargo = this.state.cargo ?? inferCargoFromHs2(this.state.hs2);
    this.cargoManual = this.state.cargo !== null;
    this.cargoDropdown = new CargoTypeDropdown({
      initialCargo,
      initialAutoInferred: !this.cargoManual,
      onChange: (cargo, manual) => this.handleCargoChange(cargo, manual),
    });

    bar.append(back, this.fromPicker.element, arrow, this.toPicker.element, this.hs2Picker.element, this.cargoDropdown.element);
    return bar;
  }

  private buildTabStrip(): HTMLDivElement {
    this.tabStrip = document.createElement('div');
    this.tabStrip.className = 're-tabstrip';
    this.tabStrip.setAttribute('role', 'tablist');
    for (const n of [1, 2, 3, 4] as const) {
      const button = document.createElement('button');
      button.type = 'button';
      button.className = 're-tabstrip__tab';
      button.dataset.tab = String(n);
      button.setAttribute('role', 'tab');
      button.setAttribute('aria-selected', n === this.state.tab ? 'true' : 'false');
      if (n === this.state.tab) button.classList.add('re-tabstrip__tab--active');
      setTrustedHtml(button, trustedHtml(`<span class="re-tabstrip__digit">${n}</span><span class="re-tabstrip__label">${TAB_LABELS[n]}</span>`, "legacy direct innerHTML migration"));
      button.addEventListener('click', () => this.setTab(n));
      this.tabStrip.append(button);
    }
    return this.tabStrip;
  }

  private buildBody(): HTMLDivElement {
    const body = document.createElement('div');
    body.className = 're-body';

    this.leftRail = new LeftRail();
    this.currentTab = new CurrentRouteTab();
    this.alternativesTab = new AlternativesTab({
      onSelectBypass: (o) => this.handleBypassSelect(o),
    });
    this.landTab = new LandTab({
      onSelectBypass: (o) => this.handleBypassSelect(o),
    });
    this.impactTab = new CountryImpactTab({
      onDrillSideways: (hs2) => this.handleDrillSideways(hs2),
    });

    this.contentEl = document.createElement('div');
    this.contentEl.className = 're-content';
    this.showActiveTab();

    body.append(this.leftRail.element, this.contentEl);
    return body;
  }

  // ─── Event handlers ────────────────────────────────────────────────────

  private handleFromCommit(iso2: string): void {
    this.state = { ...this.state, fromIso2: iso2 };
    this.writeStateToUrl();
    this.fromPicker.setValue(iso2);
    if (!this.state.toIso2) this.toPicker.focusInput();
    else if (!this.state.hs2) this.hs2Picker.focusInput();
    else this.scheduleFetch();
  }

  private handleToCommit(iso2: string): void {
    this.state = { ...this.state, toIso2: iso2 };
    this.writeStateToUrl();
    this.toPicker.setValue(iso2);
    if (!this.state.fromIso2) this.fromPicker.focusInput();
    else if (!this.state.hs2) this.hs2Picker.focusInput();
    else this.scheduleFetch();
  }

  private handleHs2Commit(hs2: string): void {
    this.state = { ...this.state, hs2 };
    this.writeStateToUrl();
    this.hs2Picker.setValue(hs2);
    if (!this.cargoManual) {
      const inferred = inferCargoFromHs2(hs2);
      this.cargoDropdown.setAutoInferred(inferred);
    }
    if (this.isQueryComplete()) this.scheduleFetch();
  }

  private handleCargoChange(cargo: ExplorerCargo, manual: boolean): void {
    this.cargoManual = manual;
    this.state = { ...this.state, cargo };
    this.writeStateToUrl();
    if (this.isQueryComplete()) this.scheduleFetch();
  }

  private setTab(n: ExplorerTab): void {
    if (n === this.state.tab) return;
    this.state = { ...this.state, tab: n };
    this.writeStateToUrl();
    this.trackEvent('route-explorer:tab-switch', { tab: n });
    if (this.tabStrip) {
      const buttons = this.tabStrip.querySelectorAll<HTMLButtonElement>('.re-tabstrip__tab');
      buttons.forEach((b) => {
        const isActive = Number.parseInt(b.dataset.tab ?? '0', 10) === n;
        b.classList.toggle('re-tabstrip__tab--active', isActive);
        b.setAttribute('aria-selected', isActive ? 'true' : 'false');
      });
    }
    this.showActiveTab();
  }

  private handleDrillSideways(hs2: string): void {
    this.state = { ...this.state, hs2 };
    this.writeStateToUrl();
    this.hs2Picker.setValue(hs2);
    if (!this.cargoManual) {
      this.cargoDropdown.setAutoInferred(inferCargoFromHs2(hs2));
    }
    this.setTab(1);
    this.scheduleFetch();
  }

  private swapFromTo(): void {
    const newFrom = this.state.toIso2;
    const newTo = this.state.fromIso2;
    this.state = { ...this.state, fromIso2: newFrom, toIso2: newTo };
    this.writeStateToUrl();
    this.fromPicker.setValue(newFrom);
    this.toPicker.setValue(newTo);
    if (this.isQueryComplete()) this.scheduleFetch();
  }

  // ─── Keyboard ──────────────────────────────────────────────────────────

  private isFormControlFocused(): boolean {
    const el = document.activeElement;
    if (!el) return false;
    const tag = el.tagName;
    if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return true;
    if ((el as HTMLElement).isContentEditable) return true;
    return false;
  }

  private blurActiveInput(): void {
    (document.activeElement as HTMLElement | null)?.blur();
  }

  private handleGlobalKeydown = (e: KeyboardEvent): void => {
    if (!this.isOpen || !this.root) return;

    if (e.key === 'Escape') {
      if (this.helpOverlay) {
        e.preventDefault(); e.stopPropagation();
        this.closeHelp();
        return;
      }
      if (this.isFormControlFocused()) return;
      e.preventDefault(); e.stopPropagation();
      this.close();
      return;
    }

    if ((e.metaKey || e.ctrlKey) && e.key === ',') {
      e.preventDefault();
      this.copyShareUrl();
      return;
    }


    if (this.isFormControlFocused()) return;
    if (e.metaKey || e.ctrlKey || e.altKey) return;

    switch (e.key) {
      case '1': case '2': case '3': case '4':
        e.preventDefault();
        this.setTab(Number.parseInt(e.key, 10) as ExplorerTab);
        return;
      case 'F': case 'f': e.preventDefault(); this.fromPicker.focusInput(); return;
      case 'T': case 't': e.preventDefault(); this.toPicker.focusInput(); return;
      case 'P': case 'p': e.preventDefault(); this.hs2Picker.focusInput(); return;
      case 'S': case 's': e.preventDefault(); this.swapFromTo(); return;
      case ' ':
        e.preventDefault();
        if (this.laneData?.primaryRouteId && this.mapRef) {
          this.mapRef.clearHighlightedRoute();
          this.mapRef.highlightRoute([this.laneData.primaryRouteId]);
        }
        return;
      case '?': e.preventDefault(); this.openHelp(); return;
      default: return;
    }
  };


  private focusInitial(): void {
    if (!this.state.fromIso2) this.fromPicker.focusInput();
    else if (!this.state.toIso2) this.toPicker.focusInput();
    else if (!this.state.hs2) this.hs2Picker.focusInput();
    else this.fromPicker.focusInput();
  }

  // ─── Help / Share ─────────────────────────────────────────────────────

  private helpPriorFocus: HTMLElement | null = null;

  private openHelp(): void {
    if (!this.root || this.helpOverlay) return;
    this.helpPriorFocus = (document.activeElement as HTMLElement) ?? null;
    this.helpOverlay = new KeyboardHelp({ onClose: () => this.closeHelp() });
    this.root.append(this.helpOverlay.element);
    const closeBtn = this.helpOverlay.element.querySelector<HTMLButtonElement>('.re-help__close');
    closeBtn?.focus();
  }

  private closeHelp(): void {
    if (!this.helpOverlay) return;
    this.helpOverlay.element.remove();
    this.helpOverlay = null;
    if (this.helpPriorFocus && document.body.contains(this.helpPriorFocus)) {
      this.helpPriorFocus.focus();
    }
    this.helpPriorFocus = null;
  }

  private copyShareUrl(): void {
    if (typeof window === 'undefined') return;
    const url = new URL(window.location.href);
    const serialized = serializeExplorerUrl(this.state);
    if (serialized) url.searchParams.set('explorer', serialized);
    if (navigator.clipboard?.writeText) {
      void navigator.clipboard.writeText(url.toString());
      this.trackEvent('route-explorer:share-copied');
    }
  }

  // ─── Analytics ─────────────────────────────────────────────────────────

  private get tier(): 'pro' | 'free' {
    return hasPremiumAccess(getAuthState()) ? 'pro' : 'free';
  }

  private trackEvent(event: UmamiEvent, props?: Record<string, unknown>): void {
    track(event, { tier: this.tier, ...props });
  }

  // ─── Test hook ────────────────────────────────────────────────────────

  private installTestHook(): void {
    if (typeof window === 'undefined') return;
    const isDev = (() => {
      try { return Boolean((import.meta as { env?: { DEV?: boolean } }).env?.DEV); } catch { return false; }
    })();
    if (!isDev) return;
    if (!window.__routeExplorerTestHook) window.__routeExplorerTestHook = {};
  }
}

let singleton: RouteExplorer | null = null;
export function getRouteExplorer(): RouteExplorer {
  if (!singleton) singleton = new RouteExplorer();
  return singleton;
}