File size: 30,647 Bytes
857cdcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * Chahuadev Hybrid Diagnostic Dashboard - Terminal + GUI
 */

class DiagnosticDashboard {
    constructor() {
        this.selectedLog = null;
        this.currentTab = 'details';
        this.maxLogs = 1000;
        
        this.init();
    }

    async init() {
        console.log(' เริ่มต้น Hybrid Diagnostic Dashboard...');
        
        // ตั้งค่า global reference สำหรับการเรียกใช้จาก HTML
        window.diagnosticDashboard = this;

        // ตรวจสอบ DEV MODE
        try {
            // เรียก API จาก Backend เพื่อตรวจสอบโหมดการทำงาน
            const runMode = await window.electronAPI.getRunMode();
            if (runMode && runMode.isDevMode) {
                console.log(' Running in Developer Mode');
                document.body.classList.add('dev-mode');
            } else {
                console.log(' Running in User Mode');
                document.body.classList.remove('dev-mode');
            }
        } catch (error) {
            console.warn(' ไม่สามารถตรวจสอบโหมดการทำงานได้', error);
        }
        
        this.setupTerminal();
        this.setupEventListeners();
        this.startRealTimeUpdates();
        
        console.log(' Hybrid Diagnostic Dashboard พร้อมใช้งาน');
    }

    //  [เวอร์ชันใหม่] ตั้งค่า Log Viewer ของเราเอง 
    setupTerminal() {
        // เราจะเรียกใช้ฟังก์ชันนี้ใน init() เหมือนเดิม
        // แต่ตอนนี้มันแค่เตรียมพร้อม ไม่ได้สร้าง Terminal ที่ซับซ้อน
        this.logViewer = document.getElementById('log-viewer');
        
        if (this.logViewer) {
            this.logViewer.innerHTML = ''; // ล้าง Log เก่าตอนเริ่มต้น
            this.writeLog({ 
                message: '===== Chahuadev Diagnostic Log (Raw HTML) =====',
                type: 'debug'
            });
            this.writeLog({ 
                message: 'Real-time logs will appear here...',
                type: 'info'
            });
        } else {
            console.error('Log viewer container not found!');
        }
    }

    //  ไม่ต้องมี resizeTerminal() อีกต่อไป เพราะ CSS จัดการให้แล้ว!

    /**
     *  Throttle function เพื่อจำกัดการเรียกฟังก์ชัน
     */
    throttle(func, limit) {
        let inThrottle;
        return function() {
            const args = arguments;
            const context = this;
            if (!inThrottle) {
                func.apply(context, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        }
    }

    setupEventListeners() {
        // Tab buttons
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                this.setActiveTab(e.target.dataset.tab);
            });
        });

        // Project Inspector buttons
        document.getElementById('scanSelfBtn')?.addEventListener('click', async () => {
            await this.handleProjectScan('self');
        });

        document.getElementById('scanPluginsBtn')?.addEventListener('click', async () => {
            await this.handleProjectScan('plugins');
        });

        document.getElementById('exportIssuesBtn')?.addEventListener('click', async () => {
            await this.handleExportIssues();
        });

        // E2E Testing button
        document.getElementById('runE2eTestsBtn')?.addEventListener('click', async () => {
            this.writeln('\x1b[1;36m กำลังเริ่มการทดสอบ E2E ทั้งระบบ...\x1b[0m');
            try {
                const result = await window.electronAPI.diagnostics.runE2eTests();
                if (result.success) {
                    this.writeln('\x1b[1;32m การทดสอบ E2E เสร็จสิ้น\x1b[0m');
                    if (result.message) {
                        this.writeln(`\x1b[1;37m${result.message}\x1b[0m`);
                    }
                } else {
                    this.writeln(`\x1b[1;31m การทดสอบ E2E ล้มเหลว: ${result.error}\x1b[0m`);
                }
            } catch (error) {
                this.writeln(`\x1b[1;31m ไม่สามารถเริ่มการทดสอบได้: ${error.message}\x1b[0m`);
            }
        });

        // Open Test Report button
        document.getElementById('openTestReportBtn')?.addEventListener('click', async () => {
            this.writeln('\x1b[1;33m กำลังเปิดรายงานผลการทดสอบ...\x1b[0m');
            try {
                const result = await window.electronAPI.diagnostics.openTestReport();
                if (result.success) {
                    this.writeln('\x1b[1;32m เปิดรายงานผลการทดสอบแล้ว\x1b[0m');
                    if (result.message) {
                        this.writeln(`\x1b[1;37m${result.message}\x1b[0m`);
                    }
                } else {
                    this.writeln(`\x1b[1;31m ไม่สามารถเปิดรายงานได้: ${result.error}\x1b[0m`);
                }
            } catch (error) {
                this.writeln(`\x1b[1;31m เกิดข้อผิดพลาด: ${error.message}\x1b[0m`);
            }
        });
    }

    /**
     * จัดการการสแกนโปรเจกต์
     * @param {'self' | 'plugins'} target - เป้าหมายที่จะสแกน
     */
    async handleProjectScan(target) {
        try {
            let projectPath = null; // เริ่มต้นเป็น null
            let targetName = '';

            //  ปรับปรุงตรรกะการเลือก Path 
            if (target === 'self') {
                targetName = 'โปรเจกต์หลัก (Framework)';
                // ขอ Path ของโปรแกรมปัจจุบันจาก Backend
                projectPath = await window.electronAPI.system.getCwd();
            } else if (target === 'plugins') {
                targetName = 'ปลั๊กอินทั้งหมด';
                //  ไม่ต้องส่ง Path! เพื่อให้ main process ใช้ default path ของ plugins
                projectPath = undefined; // ให้ Backend เลือก plugins directory เอง
            } else {
                this.writeln(`\x1b[1;31m ข้อผิดพลาด: ไม่รู้จักเป้าหมายการสแกน '${target}'\x1b[0m`);
                return;
            }

            this.writeln(`\x1b[1;33m กำลังเริ่มวิเคราะห์: ${targetName}...\x1b[0m`);
            if (projectPath) {
                this.writeln(`\x1b[1;36m   Path: ${projectPath}\x1b[0m`);
            } else {
                this.writeln(`\x1b[1;36m   ใช้ Path เริ่มต้นของปลั๊กอิน\x1b[0m`);
            }

            // ปิดการใช้งานปุ่มขณะสแกน
            const scanSelfBtn = document.getElementById('scanSelfBtn');
            const scanPluginsBtn = document.getElementById('scanPluginsBtn');
            const exportBtn = document.getElementById('exportIssuesBtn');
            
            if (scanSelfBtn) scanSelfBtn.disabled = true;
            if (scanPluginsBtn) scanPluginsBtn.disabled = true;

            // ซ่อนปุ่ม export ขณะสแกน
            if (exportBtn) {
                exportBtn.style.display = 'none';
                exportBtn.disabled = true;
            }

            if (window.electronAPI && window.electronAPI.project) {
                //  เรียก API โดยส่ง path ที่อาจจะเป็น undefined สำหรับ plugins
                const result = await window.electronAPI.project.analyze(projectPath);

                if (result.success) {
                    const scanInfo = result.scanTarget ? ` (${result.scanTarget})` : '';
                    this.writeln(`\x1b[1;32m วิเคราะห์สำเร็จ${scanInfo}: พบ ${result.analysis.totalIssues} ปัญหาใน ${result.analysis.totalFiles} ไฟล์\x1b[0m`);
                    
                    // แสดงรายละเอียดเพิ่มเติม
                    if (result.analysis.totalFiles === 0) {
                        this.writeln(`\x1b[1;33m ไม่พบไฟล์ในโฟลเดอร์นี้ หรือไฟล์ทั้งหมดถูกคัดกรองออกโดย exclusion rules\x1b[0m`);
                    }
                    
                    // แสดงผลลัพธ์ใน Inspector tab
                    this.displayAnalysisResults(result.analysis);
                    
                } else {
                    this.writeln(`\x1b[1;31m วิเคราะห์ล้มเหลว: ${result.error}\x1b[0m`);
                    
                    // แสดงปุ่ม export แม้ว่าจะล้มเหลว เผื่อมีข้อมูลบางส่วน
                    if (exportBtn) {
                        exportBtn.style.display = 'inline-block';
                        exportBtn.disabled = false;
                    }
                }
            } else {
                this.writeln('\x1b[1;31m ข้อผิดพลาด: ไม่พบ Project Inspector API\x1b[0m');
            }
            
        } catch (error) {
            this.writeln(`\x1b[1;31m ข้อผิดพลาดในการสแกน: ${error.message}\x1b[0m`);
        } finally {
            // คืนสถานะปุ่ม
            const scanSelfBtn = document.getElementById('scanSelfBtn');
            const scanPluginsBtn = document.getElementById('scanPluginsBtn');
            if (scanSelfBtn) scanSelfBtn.disabled = false;
            if (scanPluginsBtn) scanPluginsBtn.disabled = false;
        }
    }

    /**
     * แสดงผลลัพธ์การวิเคราะห์
     */
    displayAnalysisResults(analysis) {
        // อัปเดตสถิติ
        document.getElementById('totalFiles').textContent = analysis.totalFiles || 0;
        document.getElementById('totalIssues').textContent = analysis.totalIssues || 0;
        document.getElementById('totalErrors').textContent = analysis.stats?.syntaxErrors || 0;
        document.getElementById('totalWarnings').textContent = 
            (analysis.stats?.missingFiles || 0) + 
            (analysis.stats?.unusedFiles || 0) + 
            (analysis.stats?.circularDependencies || 0);

        // แสดงส่วนสถิติและฟิลเตอร์
        document.getElementById('inspectorStats').style.display = 'block';
        document.getElementById('inspectorFilters').style.display = 'block';

        // แสดงรายการปัญหา
        this.displayIssuesList(analysis.issues || []);

        // เก็บข้อมูลสำหรับการ export
        this.currentAnalysis = analysis;

        // แสดงปุ่ม Export JSON หลังจากมีผลลัพธ์ (ไม่ว่าจะพบปัญหาหรือไม่)
        const exportBtn = document.getElementById('exportIssuesBtn');
        if (exportBtn) {
            exportBtn.style.display = 'inline-block';
            exportBtn.disabled = false;
            
            // แจ้งเตือนเมื่อพบปัญหา
            if (analysis.issues && analysis.issues.length > 0) {
                this.writeln('\x1b[1;36m คลิกปุ่ม "ส่งออก JSON" เพื่อบันทึกผลการวิเคราะห์\x1b[0m');
            } else {
                this.writeln('\x1b[1;36m ผลการวิเคราะห์พร้อมส่งออก (ไม่พบปัญหา)\x1b[0m');
            }
        }

        //  แสดง notification แทนการเปลี่ยนแท็บอัตโนมัติ
        this.writeln('\x1b[1;33m ผลการวิเคราะห์พร้อมแล้ว! ไปดูในแท็บ "Inspector" ด้านบน\x1b[0m');
    }

    /**
     * แสดงรายการปัญหา
     */
    displayIssuesList(issues) {
        const resultsContainer = document.getElementById('inspectorResults');
        
        if (!issues || issues.length === 0) {
            resultsContainer.innerHTML = `
                <div class="no-selection">
                    <i class="fas fa-check-circle" style="color: #10b981;"></i>
                    <h3>ไม่พบปัญหา</h3>
                    <p>โปรเจกต์ของคุณไม่มีปัญหาที่ตรวจพบ</p>
                </div>
            `;
            return;
        }

        let html = '<div class="issues-list">';
        
        issues.forEach((issue, index) => {
            const severityClass = issue.severity === 'error' ? 'stat-error' : 'stat-warning';
            const severityIcon = issue.severity === 'error' ? 'fas fa-times-circle' : 'fas fa-exclamation-triangle';
            const severityText = issue.severity === 'error' ? 'ข้อผิดพลาด' : 'คำเตือน';
            const codeSnippetId = `code-snippet-${index}`;
            
            html += `
                <div class="issue-item" style="background: #2a2a2a; border-radius: 6px; padding: 12px; margin-bottom: 10px; border-left: 3px solid ${issue.severity === 'error' ? '#ef4444' : '#f59e0b'};">
                    <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 8px;">
                        <div>
                            <span class="${severityClass}" style="font-weight: bold;">
                                <i class="${severityIcon}"></i> ${issue.type}
                            </span>
                            <span style="color: #9ca3af; margin-left: 10px; font-size: 12px;">
                                ${issue.file}:${issue.line}:${issue.column}
                            </span>
                        </div>
                        <span style="background: #1a1a1a; color: #9ca3af; padding: 2px 6px; border-radius: 3px; font-size: 11px;">
                            ${severityText.toUpperCase()}
                        </span>
                    </div>
                    
                    <div style="color: #e0e0e0; margin-bottom: 12px;">${issue.message}</div>
                    
                    ${issue.codeSnippet ? `
                        <div class="code-snippet-container" style="margin-bottom: 12px;">
                            <div style="display: flex; align-items: center; justify-content: space-between; background: #1a1a1a; padding: 6px 10px; border-radius: 4px 4px 0 0; border-bottom: 1px solid #3a3a3a;">
                                <span style="color: #9ca3af; font-size: 12px; font-weight: 500;">
                                    <i class="fas fa-code" style="margin-right: 5px;"></i>
                                    บริบทของโค้ด
                                </span>
                                <button class="copy-code-btn" onclick="window.diagnosticDashboard.copyCodeSnippet('${codeSnippetId}')" 
                                        style="background: none; border: none; color: #9ca3af; cursor: pointer; font-size: 12px; padding: 2px 5px; border-radius: 2px;">
                                    <i class="fas fa-copy"></i> คัดลอก
                                </button>
                            </div>
                            <pre id="${codeSnippetId}" class="code-snippet" style="background: #0d1117; color: #c9d1d9; margin: 0; padding: 12px; border-radius: 0 0 4px 4px; overflow-x: auto; font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; font-size: 13px; line-height: 1.4;"><code class="language-javascript">${this.escapeHtml(issue.codeSnippet)}</code></pre>
                        </div>
                    ` : ''}
                    
                    ${issue.suggestion ? `<div style="color: #4fc3f7; font-size: 13px; font-style: italic;"> ${issue.suggestion}</div>` : ''}
                </div>
            `;
        });
        
        html += '</div>';
        resultsContainer.innerHTML = html;

        // เพิ่ม syntax highlighting
        this.applySyntaxHighlighting();

        // เพิ่ม filter functionality
        this.setupIssueFilters(issues);
    }

    /**
     * หลีกเลี่ยงการแสดง HTML tags ในโค้ด
     */
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    /**
     * ใช้ syntax highlighting กับ code snippets
     */
    applySyntaxHighlighting() {
        const codeBlocks = document.querySelectorAll('.code-snippet code');
        codeBlocks.forEach(block => {
            this.highlightJavaScript(block);
        });
    }

    /**
     * Syntax highlighting สำหรับ JavaScript
     */
    highlightJavaScript(codeElement) {
        let code = codeElement.textContent;
        
        // Keywords
        code = code.replace(/\b(const|let|var|function|class|if|else|for|while|return|import|export|from|require|try|catch|throw|async|await|new|this|super|extends|static|null|undefined|true|false)\b/g, 
            '<span style="color: #ff7b72;">$1</span>');
        
        // Strings
        code = code.replace(/(["'`])((?:\\.|(?!\1)[^\\])*?)\1/g, 
            '<span style="color: #a5d6ff;">$1$2$1</span>');
        
        // Numbers
        code = code.replace(/\b(\d+(?:\.\d+)?)\b/g, 
            '<span style="color: #79c0ff;">$1</span>');
        
        // Comments
        code = code.replace(/\/\/(.*$)/gm, 
            '<span style="color: #8b949e; font-style: italic;">//$1</span>');
        code = code.replace(/\/\*([\s\S]*?)\*\//g, 
            '<span style="color: #8b949e; font-style: italic;">/*$1*/</span>');
        
        // Function calls
        code = code.replace(/\b([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(/g, 
            '<span style="color: #d2a8ff;">$1</span>(');
        
        // Problem line highlight (line starting with >)
        code = code.replace(/^(>\s*\d+\s*\|)(.*$)/gm, 
            '<span style="background: rgba(248, 81, 73, 0.1); display: block; margin: 0 -12px; padding: 0 12px;"><span style="color: #f85149; font-weight: bold;">$1</span>$2</span>');
        
        codeElement.innerHTML = code;
    }

    /**
     * คัดลอกโค้ดไปยังคลิปบอร์ด
     */
    copyCodeSnippet(snippetId) {
        const element = document.getElementById(snippetId);
        if (element) {
            const text = element.textContent;
            navigator.clipboard.writeText(text).then(() => {
                // แสดงการแจ้งเตือนสั้นๆ
                const copyBtn = element.parentElement.querySelector('.copy-code-btn');
                const originalText = copyBtn.innerHTML;
                copyBtn.innerHTML = '<i class="fas fa-check"></i> คัดลอกแล้ว!';
                copyBtn.style.color = '#10b981';
                
                setTimeout(() => {
                    copyBtn.innerHTML = originalText;
                    copyBtn.style.color = '#9ca3af';
                }, 2000);
            }).catch(err => {
                console.error('ไม่สามารถคัดลอกได้: ', err);
            });
        }
    }

    /**
     * ตั้งค่าระบบกรองปัญหา
     */
    setupIssueFilters(issues) {
        const typeFilter = document.getElementById('typeFilter');
        const severityFilter = document.getElementById('severityFilter');

        if (typeFilter) {
            typeFilter.addEventListener('change', () => {
                this.filterIssues(issues);
            });
        }

        if (severityFilter) {
            severityFilter.addEventListener('change', () => {
                this.filterIssues(issues);
            });
        }
    }

    /**
     * กรองปัญหาตามเงื่อนไข
     */
    filterIssues(allIssues) {
        const typeFilter = document.getElementById('typeFilter')?.value || 'all';
        const severityFilter = document.getElementById('severityFilter')?.value || 'all';

        let filteredIssues = allIssues;

        if (typeFilter !== 'all') {
            filteredIssues = filteredIssues.filter(issue => issue.type === typeFilter);
        }

        if (severityFilter !== 'all') {
            filteredIssues = filteredIssues.filter(issue => issue.severity === severityFilter);
        }

        this.displayIssuesList(filteredIssues);
    }

    /**
     * จัดการการ export ปัญหา
     */
    async handleExportIssues() {
        if (!this.currentAnalysis) {
            this.writeln('\x1b[1;33m ไม่มีข้อมูลการวิเคราะห์สำหรับส่งออก\x1b[0m');
            return;
        }

        try {
            const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
            const filename = `การวิเคราะห์โปรเจกต์-${timestamp}.json`;
            
            // ใช้ Electron dialog API เพื่อให้ผู้ใช้เลือกที่บันทึก
            if (window.electronAPI && window.electronAPI.dialog) {
                const result = await window.electronAPI.dialog.showSaveDialog({
                    defaultPath: filename,
                    filters: [
                        { name: 'ไฟล์ JSON', extensions: ['json'] },
                        { name: 'ไฟล์ทั้งหมด', extensions: ['*'] }
                    ]
                });

                if (!result.canceled && result.filePath) {
                    await window.electronAPI.file.write(result.filePath, JSON.stringify(this.currentAnalysis, null, 2));
                    this.writeln(`\x1b[1;32m ส่งออกการวิเคราะห์เรียบร้อย: ${result.filePath}\x1b[0m`);
                } else {
                    this.writeln('\x1b[1;33m ยกเลิกการส่งออก\x1b[0m');
                }
            } else {
                // Fallback: สร้างลิงก์ดาวน์โหลด
                const dataStr = JSON.stringify(this.currentAnalysis, null, 2);
                const dataBlob = new Blob([dataStr], {type:'application/json'});
                const url = URL.createObjectURL(dataBlob);
                const link = document.createElement('a');
                link.href = url;
                link.download = filename;
                link.click();
                URL.revokeObjectURL(url);
                
                this.writeln(`\x1b[1;32m เริ่มดาวน์โหลดไฟล์: ${filename}\x1b[0m`);
            }
        } catch (error) {
            this.writeln(`\x1b[1;31m ข้อผิดพลาดในการส่งออก: ${error.message}\x1b[0m`);
        }
    }

    setActiveTab(tab) {
        this.currentTab = tab;
        
        // อัปเดต tab buttons
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.classList.toggle('active', btn.dataset.tab === tab);
        });

        // อัปเดต tab content
        document.querySelectorAll('.tab-content').forEach(content => {
            content.classList.toggle('active', content.id === tab + 'Tab');
        });

        // โหลดข้อมูลเฉพาะ tab
        if (tab === 'workflows') {
            this.requestWorkflowsUpdate();
        }
    }

    //  [เวอร์ชันใหม่] ฟังก์ชันสำหรับเขียน Log ที่เราควบคุมได้ 100% 
    writeLog(logData) {
        if (!this.logViewer) return;

        const timestamp = logData.timestamp ? new Date(logData.timestamp) : new Date();
        const time = timestamp.toLocaleTimeString('th-TH', { hour12: false });
        
        // สร้าง Element ใหม่สำหรับแต่ละบรรทัด Log
        const logLine = document.createElement('span');
        logLine.className = `log-line log-${logData.type || 'info'}`;
        
        // สร้างข้อความ Log
        logLine.textContent = `[${time}] ${logData.message}\n`;

        // เพิ่มบรรทัดใหม่ลงใน Log Viewer
        this.logViewer.appendChild(logLine);

        // เลื่อนหน้าจอไปที่บรรทัดล่าสุดเสมอ
        this.logViewer.scrollTop = this.logViewer.scrollHeight;
    }

    //  Helper function เพื่อความง่ายในการแทนที่ terminal.writeln() 
    writeln(message, type = 'info') {
        // ลบ ANSI color codes ออกจากข้อความ
        const cleanMessage = message.replace(/\x1b\[[0-9;]*m/g, '');
        
        // แปลงสีจาก ANSI codes เป็นประเภท Log
        let messageType = type;
        if (message.includes('\x1b[1;32m')) messageType = 'success'; // เขียว
        else if (message.includes('\x1b[1;31m')) messageType = 'error'; // แดง
        else if (message.includes('\x1b[1;33m')) messageType = 'warning'; // เหลือง
        else if (message.includes('\x1b[1;36m')) messageType = 'debug'; // ฟ้า
        
        this.writeLog({
            message: cleanMessage,
            type: messageType,
            timestamp: new Date().toISOString()
        });
    }

    //  [เวอร์ชันใหม่] อัปเดต Event Listener ให้เรียกใช้ฟังก์ชันใหม่ 
    startRealTimeUpdates() {
        if (window.electronAPI && window.electronAPI.onTerminalMessage) {
            
            window.electronAPI.onTerminalMessage((logData) => {
                // logData คือ { message, type, timestamp } ที่ส่งมาจาก Backend
                // เรียกใช้ฟังก์ชันเขียน Log ใหม่ของเราโดยตรง
                this.writeLog(logData);
            });
            
            console.log(' Raw HTML Log listener enabled.');
        } else {
            console.error(' Could not set up real-time log listener.');
        }
    }

    updateRunningWorkflows(workflowsData) {
        const container = document.getElementById('runningWorkflows');
        if (!container) return;
        
        if (!workflowsData || workflowsData.length === 0) {
            container.innerHTML = `
                <div class="no-selection">
                    <i class="fas fa-pause-circle"></i>
                    <h3>ไม่มีเวิร์กโฟลว์ที่กำลังทำงาน</h3>
                    <p>ใช้คำสั่ง <code>workflows</code> ในเทอร์มินัลเพื่อดูข้อมูลล่าสุด</p>
                </div>
            `;
            return;
        }

        container.innerHTML = '';
        workflowsData.forEach(workflow => {
            const workflowElement = this.createWorkflowElement(workflow);
            container.appendChild(workflowElement);
        });
    }

    createWorkflowElement(workflow) {
        const div = document.createElement('div');
        div.className = 'workflow-item';
        
        const statusClass = `status-${workflow.status}`;
        const progress = workflow.completedNodes || 0;
        const total = workflow.totalNodes || 0;
        const percentage = total > 0 ? Math.round((progress / total) * 100) : 0;

        div.innerHTML = `
            <div class="workflow-header">
                <span class="workflow-name">${workflow.name}</span>
                <span class="workflow-status ${statusClass}">${workflow.status}</span>
            </div>
            <div class="workflow-progress">
                <span>${progress}/${total} nodes</span>
                <span>${percentage}% complete</span>
            </div>
        `;

        return div;
    }

    updateWorkflowsTab(workflowsData) {
        this.updateRunningWorkflows(workflowsData);
    }

    formatUptime(seconds) {
        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        const secs = Math.floor(seconds % 60);
        
        if (hours > 0) {
            return `${hours}h ${minutes}m ${secs}s`;
        } else if (minutes > 0) {
            return `${minutes}m ${secs}s`;
        } else {
            return `${secs}s`;
        }
    }

    async requestWorkflowsUpdate() {
        try {
            if (window.electronAPI && window.electronAPI.diagnostics) {
                const workflows = await window.electronAPI.diagnostics.getWorkflows();
                this.updateRunningWorkflows(workflows);
            }
        } catch (error) {
            console.error('ไม่สามารถดึงข้อมูล workflows ได้:', error);
        }
    }
}

// เริ่มต้น Dashboard เมื่อ DOM พร้อม
document.addEventListener('DOMContentLoaded', () => {
    window.diagnosticDashboard = new DiagnosticDashboard();
});

// Export สำหรับใช้ใน console
window.DiagnosticDashboard = DiagnosticDashboard;