File size: 29,223 Bytes
ff50694
 
 
 
 
 
 
 
 
 
 
7a7588e
ff50694
 
3015ea3
ff50694
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3015ea3
 
 
ff50694
 
 
7a7588e
 
 
 
 
 
ff50694
 
c17ec01
ff50694
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec62a08
 
ff50694
 
 
 
ec62a08
ff50694
7a7588e
 
 
 
 
 
 
 
8094b21
7a7588e
 
 
 
ff50694
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2dd0fb8
ec62a08
ff50694
 
 
 
 
 
 
 
 
 
2dd0fb8
ff50694
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c17ec01
ff50694
 
 
 
 
ec62a08
ff50694
 
c17ec01
ff50694
 
 
 
 
 
 
 
 
 
 
ec62a08
ff50694
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2dd0fb8
ff50694
 
 
e7dfc36
2dd0fb8
 
 
 
 
 
 
 
 
 
 
 
 
 
ff50694
 
 
 
 
 
 
 
 
 
 
 
2dd0fb8
ff50694
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec62a08
ff50694
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c17ec01
ff50694
 
c17ec01
 
ff50694
c17ec01
ec62a08
c17ec01
 
 
ff50694
c17ec01
ff50694
 
 
 
 
 
 
 
 
 
 
 
 
 
ec62a08
c17ec01
ff50694
 
 
 
 
 
 
c17ec01
3fde4e4
 
 
ff50694
 
ec62a08
c17ec01
3fde4e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c17ec01
 
3fde4e4
c17ec01
3fde4e4
 
ff50694
 
c17ec01
 
ff50694
 
c17ec01
 
 
ff50694
0c01887
 
 
 
 
ff50694
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c17ec01
 
ff50694
 
 
 
 
85ec659
 
 
ff50694
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec62a08
 
ff50694
 
 
 
 
 
 
 
 
 
19fdabe
 
ec62a08
 
19fdabe
 
 
163ff2b
 
 
ff50694
 
 
 
 
19fdabe
 
 
ff50694
 
c17ec01
 
ec62a08
 
ff50694
c17ec01
 
ff50694
 
 
 
c17ec01
ff50694
163ff2b
 
c17ec01
ff50694
c17ec01
ff50694
 
d2acfa9
ff50694
 
 
 
 
d257dcc
 
0c01887
ff50694
 
 
 
 
 
0c01887
ff50694
 
 
 
 
 
a2ca6f9
78d352c
 
 
ff50694
 
8094b21
a2ca6f9
8094b21
 
a2ca6f9
 
 
 
d257dcc
a2ca6f9
ff50694
 
 
 
 
 
 
 
 
 
c17ec01
ff50694
 
c17ec01
ff50694
 
 
 
 
 
 
 
 
 
78d352c
 
 
ff50694
 
 
 
 
 
 
 
 
 
c17ec01
ff50694
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec62a08
ff50694
ec62a08
ff50694
c17ec01
ff50694
 
ec62a08
c17ec01
 
 
19fdabe
 
 
 
 
 
 
 
ff50694
 
 
 
 
 
 
19fdabe
 
 
ff50694
 
 
 
 
 
 
 
 
 
ec62a08
c17ec01
 
ff50694
 
 
 
 
 
 
 
 
 
 
 
7a7588e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a793fe
 
7a7588e
ff50694
 
 
 
 
 
 
 
c17ec01
ff50694
 
c17ec01
ff50694
 
 
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
// Main Entry Point - Wire up all event handlers and run the application
document.addEventListener("DOMContentLoaded", () => {
    // Shortcuts
    const { state } = APP.core;
    const { $, $$ } = APP.core.utils;
    const { log, setStatus, setHfStatus } = APP.ui.logging;
    const { hfDetectAsync, checkJobStatus, cancelBackendJob, pollAsyncJob } = APP.api.client;

    // Core modules
    const { captureFirstFrame, drawFirstFrame, unloadVideo, toggleDepthView, toggleFirstFrameDepthView, toggleProcessedFeed, resizeOverlays, setStreamingMode, stopStreamingMode, displayProcessedFirstFrame } = APP.core.video;
    const { syncKnobDisplays, recomputeHEL } = APP.core.hel;
    const { load: loadDemo, getFrameData: getDemoFrameData, enable: enableDemo } = APP.core.demo;

    // UI Renderers
    const { renderFrameOverlay, renderEngageOverlay, initClickHandler } = APP.ui.overlays;
    const { renderFrameTrackList } = APP.ui.cards;
    const { tickAgentCursor, moveCursorToRect } = APP.ui.cursor;
    const { matchAndUpdateTracks, predictTracks } = APP.core.tracker;
    const { defaultAimpoint } = APP.core.physics;

    // DOM Elements
    const videoEngage = $("#videoEngage");
    const videoHidden = $("#videoHidden");
    const videoFile = $("#videoFile");
    const btnReason = $("#btnReason");
    const btnCancelReason = $("#btnCancelReason");
    const btnRecompute = $("#btnRecompute");
    const btnClear = $("#btnClear");
    const btnEject = $("#btnEject");
    const btnEngage = $("#btnEngage");
    const btnReset = $("#btnReset");
    const btnPause = $("#btnPause");
    const btnToggleSidebar = $("#btnToggleSidebar");

    const detectorSelect = $("#detectorSelect");
    const missionText = $("#missionText");
    const cursorMode = $("#cursorMode");
    const frameCanvas = $("#frameCanvas");
    const frameTrackList = $("#frameTrackList");
    const frameEmpty = $("#frameEmpty");
    const frameNote = $("#frameNote");
    const engageEmpty = $("#engageEmpty");
    const engageNote = $("#engageNote");

    const chipFeed = $("#chipFeed");
    const chipDepth = $("#chipDepth");
    const chipFrameDepth = $("#chipFrameDepth");

    // Initialization
    function init() {
        log("System initializing...", "t");

        setupFileUpload();
        setupControls();
        setupKnobListeners();
        setupChipToggles();
        setupTabSwitching();

        // Initial UI sync
        syncKnobDisplays();
        setHfStatus("idle");

        // Enable click-to-select on engage overlay
        initClickHandler();

        // Start main loop
        requestAnimationFrame(loop);

        // Load demo data (if available)
        loadDemo().then(() => {
            // hidden usage: enable if video filename matches "demo" or manually
            // APP.core.demo.enable(true);
        });

        log("System READY.", "g");
    }

    function setupFileUpload() {
        if (!videoFile) return;

        videoFile.addEventListener("change", async (e) => {
            const file = e.target.files[0];
            if (!file) return;

            state.videoFile = file;
            state.videoUrl = URL.createObjectURL(file);
            state.videoLoaded = true;

            // Show meta
            const videoMeta = $("#videoMeta");
            if (videoMeta) videoMeta.textContent = file.name;

            // Load video into engage player
            if (videoEngage) {
                videoEngage.src = state.videoUrl;
                videoEngage.load();
            }

            // Hide empty states  
            if (engageEmpty) engageEmpty.style.display = "none";

            // Capture first frame dimensions (but don't draw - wait for processed frame from backend)
            try {
                await captureFirstFrame();
                // Show placeholder message - actual frame will come from backend
                if (frameNote) frameNote.textContent = "Video loaded (run Detect for processed frame)";
                if (engageNote) engageNote.textContent = "Ready for Track";
            } catch (err) {
                log(`First frame capture failed: ${err.message}`, "e");
            }

            setStatus("warn", "READY · Video loaded (run Detect)");
            log(`Video loaded: ${file.name}`, "g");

            // Load video-specific demo tracks (e.g., helicopter demo)
            if (APP.core.demo.loadForVideo) {
                await APP.core.demo.loadForVideo(file.name);
            }

            // Auto-enable demo mode if filename contains "demo" or helicopter video
            const shouldEnableDemo = file.name.toLowerCase().includes("demo") ||
                file.name.toLowerCase().includes("enhance_video_movement");
            if (shouldEnableDemo && APP.core.demo.data) {
                enableDemo(true);
                log("Auto-enabled DEMO mode for this video.", "g");
            }
        });
    }

    function setupControls() {
        // Reason button
        if (btnReason) {
            btnReason.addEventListener("click", runReason);
        }

        // Cancel Reason button
        if (btnCancelReason) {
            btnCancelReason.addEventListener("click", cancelReasoning);
        }

        // Recompute HEL button
        if (btnRecompute) {
            btnRecompute.addEventListener("click", async () => {
                if (!state.hasReasoned) return;
                await recomputeHEL();
                renderFrameOverlay();

                log("Parameters recomputed.", "g");
            });
        }

        // Clear button
        if (btnClear) {
            btnClear.addEventListener("click", () => {
                state.detections = [];
                state.selectedId = null;
                renderFrameTrackList();
                renderFrameOverlay();

                log("Detections cleared.", "t");
            });
        }

        // Eject button
        if (btnEject) {
            btnEject.addEventListener("click", async () => {
                await unloadVideo();
            });
        }

        // Engage button
        if (btnEngage) {
            btnEngage.addEventListener("click", runEngage);
        }

        // Pause button
        if (btnPause) {
            btnPause.addEventListener("click", () => {
                if (videoEngage) videoEngage.pause();
                state.tracker.running = false;
                log("Tracking paused.", "t");
            });
        }

        // Reset button
        if (btnReset) {
            btnReset.addEventListener("click", () => {
                if (videoEngage) {
                    videoEngage.pause();
                    videoEngage.currentTime = 0;
                }
                state.tracker.tracks = [];
                state.tracker.running = false;
                state.tracker.nextId = 1;
                renderFrameTrackList();
                log("Tracking reset.", "t");
            });
        }

        // Sidebar toggle (Tab 2)
        if (btnToggleSidebar) {
            btnToggleSidebar.addEventListener("click", () => {
                const engageGrid = $(".engage-grid");
                if (engageGrid) {
                    engageGrid.classList.toggle("sidebar-collapsed");
                    btnToggleSidebar.textContent = engageGrid.classList.contains("sidebar-collapsed")
                        ? "▶ Show Sidebar"
                        : "◀ Hide Sidebar";
                }
            });
        }
    }



    // Track selection event — re-renders cards (with inline features for active card)
    document.addEventListener("track-selected", (e) => {
        state.selectedId = e.detail.id;
        state.tracker.selectedTrackId = e.detail.id;
        renderFrameTrackList();
        renderFrameOverlay();
    });

    // Cursor mode toggle
    if (cursorMode) {
        cursorMode.addEventListener("change", () => {
            state.ui.cursorMode = cursorMode.value;
            if (state.ui.cursorMode === "off" && APP.ui.cursor.setCursorVisible) {
                APP.ui.cursor.setCursorVisible(false);
            }
        });
    }

    function setupKnobListeners() {
        // Listen to all inputs and selects for knob updates
        const inputs = Array.from(document.querySelectorAll("input, select"));
        inputs.forEach(el => {
            el.addEventListener("input", () => {
                syncKnobDisplays();
                if (state.hasReasoned) {
                    recomputeHEL();
                    renderFrameOverlay();

                }
            });
        });

        // Initial sync
        syncKnobDisplays();
    }

    function setupChipToggles() {
        // Toggle processed/raw feed
        if (chipFeed) {
            chipFeed.style.cursor = "pointer";
            chipFeed.addEventListener("click", () => {
                if (!state.videoLoaded) return;
                toggleProcessedFeed();
                log(`Feed set to: ${state.useProcessedFeed ? "HF" : "RAW"}`, "t");
            });
        }

        // Toggle depth view (Tab 2)
        if (chipDepth) {
            chipDepth.style.cursor = "pointer";
            chipDepth.addEventListener("click", () => {
                if (!state.videoLoaded) return;
                toggleDepthView();
                log(`Engage view set to: ${state.useDepthFeed ? "DEPTH" : "DEFAULT"}`, "t");
            });
        }

        // Toggle first frame depth view (Tab 1)
        if (chipFrameDepth) {
            chipFrameDepth.style.cursor = "pointer";
            chipFrameDepth.addEventListener("click", () => {
                if (!state.videoLoaded) return;
                if (!state.hf.depthFirstFrameUrl) {
                    log("First frame depth not ready yet. Run Detect and wait for depth processing.", "w");
                    return;
                }
                toggleFirstFrameDepthView();
                log(`First frame view set to: ${state.useFrameDepthView ? "DEPTH" : "DEFAULT"}`, "t");
            });
        }
    }

    function setupTabSwitching() {
        const tabs = Array.from(document.querySelectorAll(".tabbtn"));
        tabs.forEach(btn => {
            btn.addEventListener("click", () => {
                tabs.forEach(b => b.classList.remove("active"));
                document.querySelectorAll(".tab").forEach(t => t.classList.remove("active"));
                btn.classList.add("active");
                const tabId = `#tab-${btn.dataset.tab}`;
                const tab = $(tabId);
                if (tab) tab.classList.add("active");

                // Tab-specific actions
                if (btn.dataset.tab === "engage") {
                    resizeOverlays();
                }
            });
        });
    }

    async function runReason() {
        if (!state.videoLoaded) {
            log("No video loaded. Upload a video first.", "w");
            setStatus("warn", "READY · Upload a video");
            return;
        }

        if (state.isReasoning) {
            log("Detection already in progress. Please wait.", "w");
            return;
        }

        // Lock the Reason process
        state.isReasoning = true;
        if (btnReason) {
            btnReason.disabled = true;
            btnReason.style.opacity = "0.5";
            btnReason.style.cursor = "not-allowed";
        }
        if (btnCancelReason) btnCancelReason.style.display = "inline-block";
        if (btnEngage) btnEngage.disabled = true;

        // Clear previous detections
        state.detections = [];
        state.selectedId = null;
        renderFrameTrackList();
        renderFrameOverlay();

        setStatus("warn", "DETECTING · Running perception pipeline");

        // Agent cursor flair
        if (state.ui.cursorMode === "on" && moveCursorToRect) {
            if (btnReason) moveCursorToRect(btnReason.getBoundingClientRect());
            if (frameCanvas) setTimeout(() => moveCursorToRect(frameCanvas.getBoundingClientRect()), 260);
            if (frameTrackList) setTimeout(() => moveCursorToRect(frameTrackList.getBoundingClientRect()), 560);
        }

        try {
            const selectedOption = detectorSelect ? detectorSelect.options[detectorSelect.selectedIndex] : null;
            const selectedValue = detectorSelect ? detectorSelect.value : "hf_yolov8";
            const kind = selectedOption ? selectedOption.getAttribute("data-kind") : "object";
            const queries = missionText ? missionText.value.trim() : "";
            const enableGPT = $("#enableGPTToggle")?.checked || false;
            const enableDepth = false; // depth mode disabled

            // Determine mode and model parameter from data-kind attribute
            let mode, detectorParam, segmenterParam;
            if (kind === "segmentation") {
                mode = "segmentation";
                segmenterParam = selectedValue;
                detectorParam = "hf_yolov8"; // default, unused for segmentation
            } else if (kind === "drone") {
                mode = "drone_detection";
                detectorParam = selectedValue;
                segmenterParam = "gsam2_large";
            } else {
                mode = "object_detection";
                detectorParam = selectedValue;
                segmenterParam = "gsam2_large";
            }

            const form = new FormData();
            form.append("video", state.videoFile);
            form.append("mode", mode);
            if (queries) form.append("queries", queries);
            form.append("detector", detectorParam);
            form.append("segmenter", segmenterParam);
            form.append("enable_gpt", enableGPT ? "true" : "false");
            form.append("enable_depth", enableDepth ? "true" : "false");

            log(`Submitting job to ${state.hf.baseUrl}...`, "t");
            setHfStatus("submitting job...");

            const data = await hfDetectAsync(form);

            state.hf.asyncJobId = data.job_id;

            // Store mission specification for chatbot context
            if (data.mission_spec) {
                state.hf.missionSpec = data.mission_spec;
            }

            // Store raw detections (will process after image loads to get correct dimensions)
            const rawDetections = data.first_frame_detections || [];

            // Display processed first frame from backend (only processed frame, not raw)
            // This is async - image loading will update state.frame.w/h
            if (data.first_frame_url) {
                state.hf.firstFrameUrl = data.first_frame_url.startsWith("http")
                    ? data.first_frame_url
                    : `${state.hf.baseUrl}${data.first_frame_url}`;

                // Wait for image to load so we have correct dimensions before processing detections
                await new Promise((resolve, reject) => {
                    const img = new Image();
                    img.crossOrigin = "anonymous";
                    img.onload = () => {
                        // Update frame dimensions from loaded image
                        state.frame.w = img.naturalWidth || 1280;
                        state.frame.h = img.naturalHeight || 720;

                        // Resize canvases to match
                        const frameCanvas = $("#frameCanvas");
                        const frameOverlay = $("#frameOverlay");
                        if (frameCanvas) {
                            frameCanvas.width = state.frame.w;
                            frameCanvas.height = state.frame.h;
                            frameCanvas.getContext("2d").drawImage(img, 0, 0, state.frame.w, state.frame.h);
                        }
                        if (frameOverlay) {
                            frameOverlay.width = state.frame.w;
                            frameOverlay.height = state.frame.h;
                        }

                        // Hide empty state
                        const frameEmpty = $("#frameEmpty");
                        const frameNote = $("#frameNote");
                        if (frameEmpty) frameEmpty.style.display = "none";
                        if (frameNote) frameNote.textContent = "Processed (from backend)";

                        log(`Processed first frame displayed (${state.frame.w}×${state.frame.h})`, "g");
                        resolve();
                    };
                    img.onerror = () => {
                        log("Failed to load processed first frame, using local frame", "w");
                        drawFirstFrame();
                        resolve();
                    };
                    img.src = state.hf.firstFrameUrl;
                });
            }

            // NOW process detections (after frame dimensions are correct)
            if (rawDetections.length > 0) {
                processFirstFrameDetections(rawDetections);
            }

            // Mark first frame as ready (for radar display)
            state.firstFrameReady = true;

            // Store depth URLs if provided
            if (data.depth_video_url) {
                state.hf.depthVideoUrl = data.depth_video_url.startsWith("http")
                    ? data.depth_video_url
                    : `${state.hf.baseUrl}${data.depth_video_url}`;
                log("Depth video URL received", "t");
            }
            if (data.first_frame_depth_url) {
                state.hf.depthFirstFrameUrl = data.first_frame_depth_url.startsWith("http")
                    ? data.first_frame_depth_url
                    : `${state.hf.baseUrl}${data.first_frame_depth_url}`;
                log("First frame depth URL received", "t");
            }

            // Enable streaming mode if stream_url is provided (Tab 2 live view)
            const enableStream = $("#enableStreamToggle")?.checked;

            if (data.stream_url && enableStream) {
                const streamUrl = data.stream_url.startsWith("http")
                    ? data.stream_url
                    : `${state.hf.baseUrl}${data.stream_url}`;
                log("Activating live stream...", "t");
                setStreamingMode(streamUrl);
                log("Live view available in 'Track' tab.", "g");
                setStatus("warn", "Live processing... View in Track tab");

                // Trigger resize/render for Tab 2
                resizeOverlays();
            }

            // Start polling for completion
            pollAsyncJob().then(() => {
                log("Video processing complete.", "g");
                // Stop streaming mode once video is ready
                stopStreamingMode();

                state.hasReasoned = true;
                setStatus("good", "READY · Detection complete (you can Track)");
                log("Detection complete. Ready to Track.", "g");

                // Seed tracks for Tab 2
                seedTracksFromTab1();

                // Re-enable engage button
                if (btnEngage) btnEngage.disabled = false;
            }).catch(err => {
                log(`Polling error: ${err.message}`, "e");
                stopStreamingMode();
            });

            // Initial status (processing in background)
            setStatus("warn", "PROCESSING · Analysing video...");
            log("Reasoning started (processing in background)...", "t");



        } catch (err) {
            setStatus("bad", "ERROR · Detection failed");
            log(`Detection failed: ${err.message}`, "e");
            console.error(err);
        } finally {
            state.isReasoning = false;
            if (btnReason) {
                btnReason.disabled = false;
                btnReason.style.opacity = "1";
                btnReason.style.cursor = "pointer";
            }
            if (btnCancelReason) btnCancelReason.style.display = "none";
            // Re-enable engage button in case of failure
            if (btnEngage) btnEngage.disabled = false;
        }
    }

    function processFirstFrameDetections(dets) {
        state.detections = dets.map((d, i) => {
            const id = d.track_id || `T${String(i + 1).padStart(2, "0")}`;
            const ap = defaultAimpoint(d.label || d.class);
            const bbox = d.bbox
                ? { x: d.bbox[0], y: d.bbox[1], w: d.bbox[2] - d.bbox[0], h: d.bbox[3] - d.bbox[1] }
                : { x: 0, y: 0, w: 10, h: 10 };

            // Build features from universal schema via canonical mapping
            let features = APP.core.gptMapping.buildFeatures(d.gpt_raw);

            return {
                id,
                label: d.label || d.class,
                score: d.score || 0.5,
                bbox,
                aim: { ...ap },
                features,
                baseRange_m: null,
                baseAreaFrac: (bbox.w * bbox.h) / (state.frame.w * state.frame.h),
                baseDwell_s: 5.0,
                reqP_kW: 40,
                maxP_kW: 0,
                pkill: 0,
                // Depth fields
                depth_est_m: (d.depth_est_m !== undefined && d.depth_est_m !== null) ? d.depth_est_m : null,
                depth_rel: (d.depth_rel !== undefined && d.depth_rel !== null) ? d.depth_rel : null,
                depth_valid: d.depth_valid ?? false,
                gpt_distance_m: d.gpt_distance_m || null,
                gpt_direction: d.gpt_direction || null,
                gpt_description: d.gpt_description || null,
                // Threat Intelligence
                threat_level_score: d.threat_level_score || 0,
                threat_classification: d.threat_classification || "Unknown",
                weapon_readiness: d.weapon_readiness || "Unknown",
                // Mission relevance and assessment status
                mission_relevant: d.mission_relevant ?? null,
                relevance_reason: d.relevance_reason || null,
                assessment_status: d.assessment_status || APP.core.gptMapping.STATUS.UNASSESSED,
                assessment_frame_index: d.assessment_frame_index ?? null,
            };
        });

        state.selectedId = state.detections[0]?.id || null;

        renderFrameTrackList();
        renderFrameOverlay();

        log(`Detected ${state.detections.length} objects in first frame.`, "g");
    }

    function seedTracksFromTab1() {
        const rangeBase = $("#rangeBase");
        state.tracker.tracks = state.detections.map(d => ({
            id: d.id,
            label: d.label,
            bbox: { ...d.bbox },
            score: d.score,
            aimRel: d.aim ? { relx: d.aim.relx, rely: d.aim.rely, label: d.aim.label } : { relx: 0.5, rely: 0.5, label: "center_mass" },
            baseAreaFrac: d.baseAreaFrac || ((d.bbox.w * d.bbox.h) / (state.frame.w * state.frame.h)),
            baseRange_m: d.baseRange_m || (rangeBase ? +rangeBase.value : 1500),
            baseDwell_s: d.baseDwell_s || 4.0,
            reqP_kW: d.reqP_kW || 35,
            depth_rel: d.depth_rel,
            depth_est_m: d.depth_est_m,
            depth_valid: d.depth_valid,
            lastDepthBbox: d.depth_valid ? { ...d.bbox } : null,
            gpt_distance_m: d.gpt_distance_m,
            gpt_direction: d.gpt_direction,
            gpt_description: d.gpt_description,
            lastSeen: APP.core.utils.now(),
            vx: 0,
            vy: 0,
            dwellAccum: 0,
            killed: false,
            state: "TRACK",
            assessT: 0
        }));
        state.tracker.nextId = state.detections.length + 1;
        log(`Seeded ${state.tracker.tracks.length} tracks from Tab 1 detections.`, "t");
    }

    function cancelReasoning() {
        // Stop HF polling if running
        if (state.hf.asyncPollInterval) {
            clearInterval(state.hf.asyncPollInterval);
            state.hf.asyncPollInterval = null;
            log("HF polling stopped.", "w");
        }

        // Stop streaming mode
        stopStreamingMode();

        // Cancel backend job if it exists
        const jobId = state.hf.asyncJobId;
        if (jobId) {
            cancelBackendJob(jobId, "cancel button");
        }

        // Reset state
        state.isReasoning = false;
        state.hf.busy = false;
        state.hf.asyncJobId = null;
        state.hf.asyncStatus = "cancelled";

        // Re-enable Reason button
        if (btnReason) {
            btnReason.disabled = false;
            btnReason.style.opacity = "1";
            btnReason.style.cursor = "pointer";
        }
        if (btnCancelReason) btnCancelReason.style.display = "none";

        setStatus("warn", "CANCELLED · Detection stopped");
        setHfStatus("cancelled (stopped by user)");
        log("Detection cancelled by user.", "w");
    }

    function runEngage() {
        if (!state.hasReasoned) {
            log("Please run Detect first.", "w");
            return;
        }

        if (state.hf.asyncJobId) {
            log("Processing still in progress. Please wait.", "w");
            // If we are streaming, make sure we are on the engage tab to see it
            const engageTab = $(`.tabbtn[data-tab="engage"]`);
            if (engageTab) engageTab.click();
            return;
        }

        // Switch to engage tab
        const engageTab = $(`.tabbtn[data-tab="engage"]`);
        if (engageTab) engageTab.click();

        // Set video source
        if (videoEngage) {
            videoEngage.src = state.hf.processedUrl || state.videoUrl;
            videoEngage.play().catch(err => {
                log(`Video playback failed: ${err.message}`, "e");
            });
        }

        state.tracker.running = true;
        state.tracker.lastFrameTime = APP.core.utils.now();

        // Ensure tracks are seeded
        if (state.tracker.tracks.length === 0) {
            seedTracksFromTab1();
        }

        log("Tracking started.", "g");
    }

    function loop() {
        const { now } = APP.core.utils;
        const t = now();

        // Guard against huge dt on first frame
        if (state.tracker.lastFrameTime === 0) state.tracker.lastFrameTime = t;

        const dt = Math.min((t - state.tracker.lastFrameTime) / 1000, 0.1);
        state.tracker.lastFrameTime = t;

        // Update tracker when engaged
        if (state.tracker.running && videoEngage && !videoEngage.paused) {

            // DEMO MODE BYPASS
            if (APP.core.demo.active && APP.core.demo.data) {
                const demoTracks = getDemoFrameData(videoEngage.currentTime);
                if (demoTracks) {
                    // Deep clone to avoid mutating source data
                    const tracksClone = JSON.parse(JSON.stringify(demoTracks));

                    state.tracker.tracks = tracksClone.map(d => ({
                        ...d,
                        // Ensure defaults
                        lastSeen: t,
                        state: "TRACK",
                        depth_valid: true,
                        depth_est_m: d.gpt_distance_m || 1000,
                    }));

                    // Normalize if needed (frontend usually expects 0..1)
                    const w = videoEngage.videoWidth || state.frame.w || 1280;
                    const h = videoEngage.videoHeight || state.frame.h || 720;

                    state.tracker.tracks.forEach(tr => {
                        // Check if inputs are absolute pixels (if x > 1 or w > 1)
                        // We assume demo data is in pixels (as per spec)
                        if (tr.bbox.x > 1 || tr.bbox.w > 1) {
                            tr.bbox.x /= w;
                            tr.bbox.y /= h;
                            tr.bbox.w /= w;
                            tr.bbox.h /= h;
                        }

                        // Note: history in 'tr' is also in pixels in the source JSON.
                        // But we don't normalize history here because radar.js currently handles raw pixels for history?
                        // Actually, we should probably standardize everything to normalized if possible, 
                        // but let's check radar.js first.
                    });

                } else {
                    // NORMAL MODE
                    predictTracks(dt);

                    // Sync with backend every few frames (approx 5Hz)
                    if (t - state.tracker.lastHFSync > 200) {
                        // Estimate frame index
                        const fps = 30; // hardcoded for now, ideal: state.fps
                        const frameIdx = Math.floor(videoEngage.currentTime * fps);
                        // Only sync if we have a job ID
                        if (state.hf.asyncJobId) {
                            APP.core.tracker.syncWithBackend(frameIdx);
                        }
                        state.tracker.lastHFSync = t;
                    }
                }
            }
        } // End if(running)

        // Render UI
        if (renderFrameOverlay) renderFrameOverlay();
        if (renderEngageOverlay) renderEngageOverlay();
        if (tickAgentCursor) tickAgentCursor();

        requestAnimationFrame(loop);
    }

    // Expose state for debugging
    window.__LP_STATE__ = state;

    // Start
    init();
});