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6505
5fb3ca1
5dc6505
 
5fb3ca1
5dc6505
5fb3ca1
5dc6505
 
 
5fb3ca1
 
 
 
 
 
 
 
 
 
 
 
5dc6505
 
 
5fb3ca1
 
 
 
 
 
 
 
5dc6505
 
 
5fb3ca1
 
 
 
 
 
 
5dc6505
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5fb3ca1
5dc6505
 
 
5fb3ca1
5dc6505
 
5fb3ca1
5dc6505
 
 
 
 
 
5fb3ca1
5dc6505
 
 
5fb3ca1
 
 
 
 
 
 
 
 
 
 
5dc6505
 
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
import { ControlWavePlugin } from '../plugin-loader.js';

export default class SignXPlugin extends ControlWavePlugin {
    constructor() {
        super({
            id: 'signx-inference',
            name: 'SignX',
            version: '1.0.0',
            author: 'ControlWave Team',
            description: 'Sign language recognition inference powered by SignX',
            needsViser: false,
            order: 100
        });

        this.currentVideoPath = null;
        this.isInferring = false;
        this.videoEl = null;
        this.logsPre = null;
        this.currentJobId = null;
        this.logCursor = 0;
        this.logPollingTimer = null;
        this.runButtonOriginalText = null;
    }

    async render(container) {
        container.innerHTML = '';
        container.className = 'tab-content active';

        // Inject styles
        const style = document.createElement('style');
        style.textContent = `
            .signx-root {
                display: flex;
                flex-direction: column;
                gap: 20px;
                width: 100%;
                height: 100%;
                padding: 20px;
                box-sizing: border-box;
            }

            .signx-top {
                display: flex;
                gap: 20px;
                width: 100%;
                flex: 1;
            }

            .signx-left, .signx-right, .signx-bottom {
                background: #fff;
                border-radius: 12px;
                box-shadow: 0 4px 16px rgba(15, 23, 42, 0.08);
                padding: 20px;
                display: flex;
                flex-direction: column;
            }

            .signx-left {
                flex: 1.2;
            }

            .signx-right {
                flex: 1;
                overflow-y: auto;
            }

            .signx-bottom {
                width: 100%;
                min-height: 200px;
            }

            .signx-video-frame {
                position: relative;
                width: 100%;
                padding-top: 56.25%;
                background: #0f172a;
                border-radius: 10px;
                overflow: hidden;
            }

            .signx-bottom-title {
                font-size: 18px;
                font-weight: 600;
                color: #0f172a;
                margin-bottom: 12px;
            }

            .signx-results-grid {
                display: grid;
                grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
                gap: 16px;
                width: 100%;
            }

            .signx-results-grid .signx-result-section {
                margin: 0;
            }

            .signx-result-section.full-width {
                grid-column: 1 / -1;
            }

            @media (max-width: 1200px) {
                .signx-top {
                    flex-direction: column;
                }
                .signx-results-grid {
                    grid-template-columns: 1fr;
                }
            }

            .signx-video-frame video {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                object-fit: contain;
                background: #0f172a;
            }

            .signx-video-placeholder {
                position: absolute;
                inset: 0;
                display: flex;
                align-items: center;
                justify-content: center;
                color: #94a3b8;
                font-size: 15px;
                text-align: center;
                padding: 20px;
            }

            .signx-video-controls {
                margin-top: 15px;
                display: flex;
                gap: 10px;
                flex-direction: column;
            }

            .signx-section-title {
                font-size: 18px;
                font-weight: 600;
                color: #0f172a;
                margin-bottom: 16px;
                padding-bottom: 10px;
                border-bottom: 2px solid #2196F3;
            }

            .signx-form-group {
                margin-bottom: 15px;
            }

            .signx-form-group label {
                display: block;
                margin-bottom: 5px;
                font-weight: 500;
                color: #475569;
                font-size: 13px;
            }

            .signx-form-group select {
                width: 100%;
                padding: 8px 12px;
                border: 1px solid #cbd5e1;
                border-radius: 6px;
                font-size: 14px;
                background: white;
                cursor: pointer;
                transition: all 0.2s;
            }

            .signx-form-group select:focus {
                outline: none;
                border-color: #2196F3;
                box-shadow: 0 0 0 3px rgba(33, 150, 243, 0.1);
            }

            .signx-btn {
                width: 100%;
                padding: 10px 20px;
                border: none;
                border-radius: 6px;
                font-size: 14px;
                font-weight: 500;
                cursor: pointer;
                transition: all 0.2s;
            }

            .signx-btn-primary {
                background: #2196F3;
                color: white;
            }

            .signx-btn-primary:hover:not(:disabled) {
                background: #1976D2;
                transform: translateY(-1px);
                box-shadow: 0 4px 8px rgba(33, 150, 243, 0.3);
            }

            .signx-btn:disabled {
                background: #cbd5e1;
                cursor: not-allowed;
                opacity: 0.6;
            }

            .signx-status {
                margin-top: 20px;
                padding: 12px 15px;
                background: #f1f5f9;
                border-radius: 6px;
                border-left: 3px solid #2196F3;
                font-size: 13px;
                line-height: 1.6;
            }

            .signx-status.info {
                border-left-color: #2196F3;
                background: #E3F2FD;
            }

            .signx-status.success {
                border-left-color: #4CAF50;
                background: #E8F5E9;
            }

            .signx-status.error {
                border-left-color: #f44336;
                background: #FFEBEE;
            }

            .signx-status.loading {
                border-left-color: #FF9800;
                background: #FFF3E0;
            }

            .signx-logs {
                margin-top: 20px;
            }

            .signx-logs pre {
                background: #0f172a;
                color: #cbd5e1;
                border-radius: 8px;
                padding: 14px;
                font-size: 12px;
                line-height: 1.6;
                max-height: 400px;
                overflow-y: auto;
                white-space: pre-wrap;
                word-wrap: break-word;
                font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
            }

            .signx-result-section {
                margin-top: 20px;
                padding: 15px;
                background: #f8fafc;
                border-radius: 8px;
                border: 1px solid #e2e8f0;
            }

            .signx-result-section h4 {
                margin: 0 0 10px 0;
                color: #0f172a;
                font-size: 14px;
                font-weight: 600;
            }

            .signx-result-content {
                font-family: monospace;
                font-size: 13px;
                line-height: 1.6;
                color: #1e293b;
                background: white;
                padding: 10px;
                border-radius: 4px;
                max-height: 150px;
                overflow-y: auto;
            }

            .spinner {
                display: inline-block;
                width: 14px;
                height: 14px;
                border: 2px solid #f3f3f3;
                border-top: 2px solid #2196F3;
                border-radius: 50%;
                animation: spin 1s linear infinite;
                margin-right: 8px;
                vertical-align: middle;
            }

            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }

            .signx-analysis-item {
                margin-top: 20px;
                padding-top: 20px;
                border-top: 1px solid #e2e8f0;
            }

            .signx-analysis-item:first-child {
                margin-top: 0;
                padding-top: 0;
                border-top: none;
            }

            .signx-analysis-item h5 {
                margin: 0 0 10px 0;
                color: #475569;
                font-size: 13px;
                font-weight: 600;
            }

            .signx-analysis-item img {
                display: block;
                max-width: 100%;
                height: auto;
                border: 1px solid #e2e8f0;
                border-radius: 4px;
                transition: transform 0.2s, box-shadow 0.2s;
            }

            .signx-analysis-item img:hover {
                transform: scale(1.02);
                box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            }

            .signx-link-button {
                display: inline-block;
                padding: 8px 16px;
                background: #2196F3;
                color: white;
                text-decoration: none;
                border-radius: 4px;
                font-size: 13px;
                font-weight: 500;
                transition: background 0.2s;
            }

            .signx-link-button:hover {
                background: #1976D2;
            }

            .signx-keyframes-grid {
                display: grid;
                grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
                gap: 10px;
                margin-top: 10px;
            }

            .signx-keyframe-preview {
                text-align: center;
            }

            .signx-keyframe-preview img {
                width: 100%;
                height: auto;
                border: 1px solid #e2e8f0;
                border-radius: 4px;
            }

            .signx-keyframe-preview span {
                display: block;
                margin-top: 4px;
                font-size: 11px;
                color: #64748b;
            }
        `;

        container.appendChild(style);

        // Build layout
        const root = document.createElement('div');
        root.className = 'signx-root';
        root.innerHTML = `
            <div class="signx-top">
                <div class="signx-left">
                    <h3 class="signx-section-title">Video Preview</h3>
                    <div class="signx-video-frame">
                        <video id="signx-video" controls loop></video>
                        <div class="signx-video-placeholder" id="signx-video-placeholder">
                            Select a video to preview it here
                        </div>
                    </div>
                    <div class="signx-video-controls">
                        <div class="signx-form-group">
                            <label>Video Folder</label>
                            <select id="signx-video-folder">
                                <option value="videos">videos (test)</option>
                                <option value="good_videos" selected>good_videos (recommended)</option>
                            </select>
                        </div>
                        <div class="signx-form-group">
                            <label>Video File</label>
                            <select id="signx-video-file">
                                <option value="">Loading...</option>
                            </select>
                        </div>
                        <button id="signx-run-inference" class="signx-btn signx-btn-primary" disabled>
                            Run Inference
                        </button>
                    </div>
                </div>

                <div class="signx-right">
                    <h3 class="signx-section-title">Status & Logs</h3>

                    <div id="signx-status" class="signx-status info">
                        Select a video file to begin
                    </div>

                    <div class="signx-logs">
                        <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #475569; font-size: 13px;">
                            Inference Logs
                        </label>
                        <pre id="signx-logs">(waiting for inference job...)</pre>
                    </div>
                </div>
            </div>

            <div class="signx-bottom">
                <div class="signx-bottom-title">Inference Outputs & Visualizations</div>
                <div id="signx-results-container" class="signx-results-grid"></div>
            </div>
        `;

        container.appendChild(root);

        // Cache element references
        this.videoEl = document.getElementById('signx-video');
        this.videoPlaceholder = document.getElementById('signx-video-placeholder');
        this.logsPre = document.getElementById('signx-logs');

        // Hide video until a file is selected
        if (this.videoEl) {
            this.videoEl.style.display = 'none';
        }

        // Register event listeners
        this.setupEventListeners();

        // Initial load of video options
        this.loadVideoList();
    }

    setupEventListeners() {
        const folderSelect = document.getElementById('signx-video-folder');
        const fileSelect = document.getElementById('signx-video-file');
        const runButton = document.getElementById('signx-run-inference');

        if (folderSelect) {
            folderSelect.addEventListener('change', () => {
                this.loadVideoList();
            });
        }

        if (fileSelect) {
            fileSelect.addEventListener('change', (e) => {
                this.currentVideoPath = e.target.value;
                const runButton = document.getElementById('signx-run-inference');
                if (runButton) {
                    runButton.disabled = !this.currentVideoPath;
                }

                if (this.currentVideoPath) {
                    this.updateStatus('Selected video: ' + this.currentVideoPath.split('/').pop(), 'info');
                    this.updateVideo(this.currentVideoPath);
                }
            });
        }

        if (runButton) {
            runButton.addEventListener('click', () => {
                this.runInference();
            });
        }
    }

    async loadVideoList() {
        const folderSelect = document.getElementById('signx-video-folder');
        const fileSelect = document.getElementById('signx-video-file');

        if (!folderSelect || !fileSelect) {
            console.error('SignX: unable to locate folder or file selectors');
            return;
        }

        const folder = folderSelect.value;
        console.log(`SignX: loading video list, folder=${folder}`);
        fileSelect.innerHTML = '<option value="">Loading...</option>';

        try {
            const data = await this.sendPluginMessage('list_videos', { folder: folder });

            console.log('SignX: received response:', data);

            if (data && data.status === 'success') {
                fileSelect.innerHTML = '<option value="">Select a video file</option>';

                if (data.videos && data.videos.length > 0) {
                    data.videos.forEach(video => {
                        const option = document.createElement('option');
                        option.value = video.path;
                        option.textContent = video.name;
                        fileSelect.appendChild(option);
                    });
                    console.log(`SignX: loaded ${data.videos.length} videos`);
                    this.updateStatus(`Found ${data.videos.length} video files`, 'info');
                } else {
                    console.warn('SignX: video list is empty');
                    this.updateStatus('No video files found', 'info');
                }
            } else {
                console.error('SignX: response status not success:', data);
                fileSelect.innerHTML = '<option value="">Failed to load</option>';
                this.updateStatus('Failed to load video list: ' + (data ? data.message : 'Unknown error'), 'error');
            }
        } catch (error) {
            console.error('SignX: error while loading videos:', error);
            fileSelect.innerHTML = '<option value="">Failed to load</option>';
            this.updateStatus('Failed to load video list: ' + error.message, 'error');
        }
    }

    async updateVideo(videoPath) {
        if (!this.videoEl || !this.videoPlaceholder) {
            return;
        }

        try {
            const videoUrl = videoPath.replace(/.*\/plugins\/SignX/, '/plugins/SignX');

            console.log('SignX: loading video URL:', videoUrl);

            this.videoEl.src = videoUrl;
            this.videoEl.style.display = 'block';
            this.videoPlaceholder.style.display = 'none';

            this.videoEl.onloadeddata = () => {
                console.log('SignX: video loaded');
            };

            this.videoEl.onerror = () => {
                this.videoEl.style.display = 'none';
                this.videoPlaceholder.style.display = 'flex';
                this.videoPlaceholder.textContent = 'Video failed to load';
                console.error('SignX: failed to load video URL:', videoUrl);
            };

            this.videoEl.load();
        } catch (error) {
            this.videoEl.style.display = 'none';
            this.videoPlaceholder.style.display = 'flex';
            this.videoPlaceholder.textContent = 'Video failed to load';
            console.error('SignX: video load error:', error);
        }
    }

    async runInference() {
        if (!this.currentVideoPath || this.isInferring) {
            return;
        }

        const runButton = document.getElementById('signx-run-inference');
        if (!runButton) {
            return;
        }

        this.isInferring = true;
        this.runButtonOriginalText = runButton.innerHTML;
        runButton.disabled = true;
        runButton.innerHTML = '<span class="spinner"></span>Running...';

        this.updateStatus('Running SignX inference. This may take a few minutes...', 'loading');
        if (this.logsPre) {
            this.logsPre.textContent = 'Starting inference...\n';
        }

        try {
            const response = await this.sendPluginMessage('run_inference', {
                video_path: this.currentVideoPath
            });

            if (response.status === 'running' && response.job_id) {
                this.currentJobId = response.job_id;
                this.logCursor = 0;
                this.startLogPolling();
                return;
            }

            if (response.status === 'success') {
                this.updateStatus('Inference complete!', 'success');
                this.displayResults(response);
            } else {
                const errMsg = response.message || 'Unknown error';
                this.updateStatus('Inference failed: ' + errMsg, 'error');
                if (response.logs && this.logsPre) {
                    this.logsPre.textContent = Array.isArray(response.logs) ? response.logs.join('\n') : response.logs;
                }
            }
        } catch (error) {
            console.error('SignX: inference failed:', error);
            this.updateStatus('Inference failed: ' + error.message, 'error');
            if (this.logsPre) {
                this.logsPre.textContent = error.message;
            }
        } finally {
            if (!this.currentJobId) {
                this.resetRunButton();
                this.stopLogPolling();
            }
        }
    }

    startLogPolling() {
        this.stopLogPolling();
        this.pollJobStatus();
        this.logPollingTimer = setInterval(() => {
            this.pollJobStatus();
        }, 1200);
    }

    stopLogPolling() {
        if (this.logPollingTimer) {
            clearInterval(this.logPollingTimer);
            this.logPollingTimer = null;
        }
    }

    async pollJobStatus() {
        if (!this.currentJobId) {
            return;
        }

        try {
            const response = await this.sendPluginMessage('get_job_status', {
                job_id: this.currentJobId,
                last_index: this.logCursor
            });

            if (response.status !== 'success') {
                throw new Error(response.message || 'Failed to fetch job status');
            }

            if (Array.isArray(response.logs) && response.logs.length > 0) {
                this.appendLogs(response.logs);
            }

            if (typeof response.next_index === 'number') {
                this.logCursor = response.next_index;
            } else if (response.logs) {
                this.logCursor += response.logs.length;
            }

            const jobStatus = response.job_status;
            if (jobStatus === 'success' && response.result) {
                this.updateStatus('Inference complete!', 'success');
                this.displayResults(response.result);
                this.finishCurrentJob();
            } else if (jobStatus === 'error') {
                const errMsg = response.error_message || 'Inference failed';
                this.updateStatus(`Inference failed: ${errMsg}`, 'error');
                this.finishCurrentJob();
            } else if (jobStatus === 'running') {
                this.updateStatus('Running inference...', 'loading');
            }
        } catch (error) {
            console.error('SignX: failed to poll job status', error);
            this.updateStatus(`Log polling failed: ${error.message}`, 'error');
            this.finishCurrentJob();
        }
    }

    appendLogs(newLines) {
        if (!this.logsPre || !newLines) {
            return;
        }

        const text = Array.isArray(newLines) ? newLines.join('\n') : newLines;
        if (!text) {
            return;
        }

        if (!this.logsPre.textContent || this.logsPre.textContent === '(waiting for inference job...)') {
            this.logsPre.textContent = '';
        }

        if (this.logsPre.textContent && !this.logsPre.textContent.endsWith('\n')) {
            this.logsPre.textContent += '\n';
        }

        this.logsPre.textContent += text + '\n';
        this.logsPre.scrollTop = this.logsPre.scrollHeight;
    }

    resetRunButton() {
        const runButton = document.getElementById('signx-run-inference');
        if (runButton) {
            runButton.disabled = false;
            runButton.innerHTML = this.runButtonOriginalText || 'Run Inference';
        }
        this.runButtonOriginalText = null;
        this.isInferring = false;
    }

    finishCurrentJob() {
        this.stopLogPolling();
        this.currentJobId = null;
        this.resetRunButton();
    }

    displayResults(data) {
        const resultsContainer = document.getElementById('signx-results-container');

        if (!resultsContainer) return;

        resultsContainer.innerHTML = '';

        if (data.logs && data.logs.length > 0 && this.logsPre && !this.logsPre.textContent) {
            this.logsPre.textContent = data.logs.join('\n');
        }

        if (data.output_clean) {
            resultsContainer.appendChild(
                this.createResultCard(
                    'Recognition Result (Gloss Sequence)',
                    this.escapeHtml(data.output_clean)
                )
            );
        }

        if (data.execution_time) {
            resultsContainer.appendChild(
                this.createResultCard(
                    'Execution Time',
                    `${data.execution_time.toFixed(2)} s`
                )
            );
        }

        if (data.translation_path) {
            resultsContainer.appendChild(
                this.createResultCard(
                    'Translation File',
                    `<code>${this.escapeHtml(data.translation_path)}</code>`
                )
            );
        }

        if (data.analysis_images && data.analysis_images.length > 0) {
            data.analysis_images.forEach(file => {
                const card = document.createElement('div');
                card.className = 'signx-result-section';
                if (file.type === 'keyframes') {
                    card.classList.add('full-width');
                }

                let body = '';
                if (file.type === 'image') {
                    body = `
                        <img src="${file.url}"
                             alt="${file.name}"
                             onclick="window.open('${file.url}', '_blank')"
                             style="cursor: pointer; max-width: 100%; border-radius: 6px;">
                    `;
                } else if (file.type === 'html') {
                    body = `
                        <a href="${file.url}" target="_blank" class="signx-link-button">
                            Open interactive visualization →
                        </a>
                    `;
                } else if (file.type === 'keyframes') {
                    const previews = (file.previews || []).map(preview => `
                        <div class="signx-keyframe-preview">
                            <img src="${preview.url}" alt="${preview.name}"
                                 onclick="window.open('${preview.url}', '_blank')"
                                 style="cursor: pointer;">
                            <span>${preview.name}</span>
                        </div>
                    `).join('');
                    body = `
                        <div class="signx-keyframes-grid">
                            ${previews || '<span>No keyframes available.</span>'}
                        </div>
                    `;
                }

                card.innerHTML = `
                    <h4>${file.name}</h4>
                    <div class="signx-result-content">
                        ${body}
                    </div>
                `;
                resultsContainer.appendChild(card);
            });
        }

        if (data.analysis_dir) {
            resultsContainer.appendChild(
                this.createResultCard(
                    'Full Analysis Path',
                    `<code>${this.escapeHtml(data.analysis_dir)}</code>`,
                    { fullWidth: true }
                )
            );
        }
    }

    updateStatus(message, type = 'info') {
        const statusBox = document.getElementById('signx-status');
        if (!statusBox) return;

        statusBox.className = 'signx-status ' + type;

        if (type === 'loading') {
            statusBox.innerHTML = `<span class="spinner"></span>${message}`;
        } else {
            statusBox.textContent = message;
        }
    }

    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    /**
     * Send a plugin request over the shared WebSocket
     */
    async sendPluginMessage(action, data) {
        if (!window.controlWaveWebSocket || !window.controlWaveWebSocket.isConnected) {
            throw new Error('WebSocket not connected');
        }

        console.log(`SignX: sending request action=${action}`, data);

        const response = await window.controlWaveWebSocket.sendRequest('signx', {
            action: action,
            data: data
        });

        console.log('SignX: received response', response);
        return response;
    }

    createResultCard(title, contentHtml, options = {}) {
        const card = document.createElement('div');
        card.className = 'signx-result-section';
        if (options.fullWidth) {
            card.classList.add('full-width');
        }
        card.innerHTML = `
            <h4>${title}</h4>
            <div class="signx-result-content">${contentHtml}</div>
        `;
        return card;
    }
}