File size: 26,433 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
/**
 *  Button Generator - Smart Button Creation System
 *  Chahua Development Thailand
 *  CEO: Saharath C.
 * 
 *  Purpose: สร้างปุ่มแบบอัจฉริยะตามการทำงานของโปรเจค
 */

const fs = require('fs');
const path = require('path');

class ButtonGenerator {
    constructor(language = 'en') {
        this.buttonRegistry = new Map();
        this.language = language; // ภาษาปัจจุบัน: 'en' หรือ 'th'
        this.templateLibrary = this.initializeTemplateLibrary();
        this.actionHandlers = new Map();
        this.translations = this.initializeTranslations();
        
        console.log(` Button Generator initialized (Language: ${language})`);
    }

    // ระบบแปลหลายภาษา
    initializeTranslations() {
        return {
            'en': {
                // Node.js
                'npm-install': 'Install',
                'npm-start': 'Start',
                'npm-test': 'Test',
                'npm-build': 'Build',
                'npm-lint': 'Lint',
                'npm-dev': 'Dev',
                'npm-serve': 'Serve',
                // Python
                'pip-install': 'Install',
                'python-run': 'Run Main',
                'python-test': 'Test',
                'python-format': 'Format',
                // Executable
                'launch-exe': 'Launch App',
                'run-as-admin': 'Run as Admin',
                // Batch
                'run-batch': 'Run Script',
                'edit-batch': 'Edit Script',
                // Utility
                'open-terminal': 'Terminal',
                'file-explorer': 'Open Folder',
                'refresh': 'Refresh',
                'settings': 'Settings',
                // Web
                'npm-watch': 'Watch',
                'deploy': 'Deploy',
                // Categories
                'Node.js Basic': 'Node.js Basic',
                'Node.js Advanced': 'Node.js Advanced',
                'Python Basic': 'Python Basic',
                'Python Advanced': 'Python Advanced',
                'Application': 'Application',
                'Batch Scripts': 'Batch Scripts',
                'Utility': 'Utility',
                'Web Development': 'Web Development'
            },
            'th': {
                // Node.js
                'npm-install': 'ติดตั้ง',
                'npm-start': 'เริ่มต้น',
                'npm-test': 'ทดสอบ',
                'npm-build': 'สร้าง',
                'npm-lint': 'ตรวจสอบ',
                'npm-dev': 'พัฒนา',
                'npm-serve': 'เรียกใช้',
                // Python
                'pip-install': 'ติดตั้ง',
                'python-run': 'รันหลัก',
                'python-test': 'ทดสอบ',
                'python-format': 'จัดรูป',
                // Executable
                'launch-exe': 'เปิดแอป',
                'run-as-admin': 'รันเป็นผู้ดูแลระบบ',
                // Batch
                'run-batch': 'รันสคริปต์',
                'edit-batch': 'แก้ไขสคริปต์',
                // Utility
                'open-terminal': 'เทอร์มินัล',
                'file-explorer': 'เปิดโฟลเดอร์',
                'refresh': 'รีเฟรช',
                'settings': 'ตั้งค่า',
                // Web
                'npm-watch': 'เฝ้าดู',
                'deploy': 'ปรับใช้',
                // Categories
                'Node.js Basic': 'Node.js พื้นฐาน',
                'Node.js Advanced': 'Node.js ขั้นสูง',
                'Python Basic': 'Python พื้นฐาน',
                'Python Advanced': 'Python ขั้นสูง',
                'Application': 'แอปพลิเคชัน',
                'Batch Scripts': 'สคริปต์ Batch',
                'Utility': 'เครื่องมือ',
                'Web Development': 'พัฒนา Web'
            }
        };
    }

    // ฟังก์ชันแปลข้อความ
    translate(key) {
        const trans = this.translations[this.language] || this.translations['en'];
        return trans[key] || key;
    }

    // ตั้งภาษา
    setLanguage(language) {
        if (this.translations[language]) {
            this.language = language;
            console.log(` Button language changed to: ${language}`);
        } else {
            console.warn(` Unsupported language: ${language}, using English`);
            this.language = 'en';
        }
    }

    //  ไลบรารีเทมเพลตปุ่มสำหรับโปรเจคต่างๆ
    initializeTemplateLibrary() {
        return {
            //  Node.js Project Templates
            'node-basic': {
                category: 'Node.js Basic',
                buttons: [
                    { id: 'npm-install', nameKey: 'npm-install', command: 'npm-install', icon: '' },
                    { id: 'npm-start', nameKey: 'npm-start', command: 'npm-start', icon: '' }
                ]
            },
            'node-advanced': {
                category: 'Node.js Advanced',
                buttons: [
                    { id: 'npm-test', nameKey: 'npm-test', command: 'npm-test', icon: '' },
                    { id: 'npm-build', nameKey: 'npm-build', command: 'npm-build', icon: '' },
                    { id: 'npm-lint', nameKey: 'npm-lint', command: 'npm-lint', icon: '' }
                ]
            },

            //  Python Project Templates
            'python-basic': {
                category: 'Python Basic',
                buttons: [
                    { id: 'pip-install', nameKey: 'pip-install', command: 'pip-install', icon: '' },
                    { id: 'python-run', nameKey: 'python-run', command: 'python-run', icon: '' }
                ]
            },

            //  เพิ่ม Template ใหม่สำหรับ EXE
            'executable-runner': {
                category: 'Application',
                buttons: [
                    { id: 'launch-exe', nameKey: 'launch-exe', command: 'launch-exe', icon: '' },
                    { id: 'run-as-admin', nameKey: 'run-as-admin', command: 'run-as-admin', icon: '' }
                ]
            },

            //  เพิ่ม Template ใหม่สำหรับ BAT
            'batch-runner': {
                category: 'Batch Scripts',
                buttons: [
                    { id: 'run-batch', nameKey: 'run-batch', command: 'run-batch', icon: '' },
                    { id: 'edit-batch', nameKey: 'edit-batch', command: 'edit-batch', icon: '' }
                ]
            },

            //  Utility Templates (ปุ่มพื้นฐาน)
            'utility': {
                category: 'Utility',
                buttons: [
                    { id: 'open-terminal', nameKey: 'open-terminal', command: 'open_terminal', icon: '' },
                    { id: 'file-explorer', nameKey: 'file-explorer', command: 'open_explorer', icon: '' }
                ]
            }
        };
    }

    //  สร้างปุ่มตามข้อมูลโปรเจค
    generateProjectButtons(projectInfo, features) {
        const { name, type, path: projectPath, previewImage } = projectInfo; //  เพิ่ม previewImage
        let buttons = [];
        console.log(` Generating buttons for project: ${name} (Type: ${type})`);

        //  เพิ่ม fallback สำหรับ unknown type
        let projectType = type;
        if (projectType === 'unknown') {
            projectType = 'executable_project'; // fallback เป็น executable_project
            console.log(`  ->  [Fallback] Using executable_project type instead of unknown`);
            projectInfo.type = projectType; // อัปเดต type ใน object
        }

        // ---  อัปเกรดตรรกะการตัดสินใจเป็นแบบ 3 ทาง ---

        if (features.hasBatchRunner) {
            // 1. ทางพิเศษสำหรับ .bat
            console.log(`  ->  Using Batch Runner strategy`);
            const batchTemplate = this.templateLibrary['batch-runner'];
            if (batchTemplate) {
                const batchButtons = this.customizeButtons(batchTemplate.buttons, projectInfo, features);
                buttons.push(...this.customizeBatchButtons(batchButtons, projectInfo));
            }

        } else if (projectType === 'executable_project') {
            // 2. ทางพิเศษสำหรับ .exe
            console.log(`  ->  Using Executable Runner strategy`);
            const exeTemplate = this.templateLibrary['executable-runner'];
            if (exeTemplate) {
                const exeButtons = this.customizeButtons(exeTemplate.buttons, projectInfo, features);
                buttons.push(...this.customizeExecutableButtons(exeButtons, projectInfo));
            }

        } else {
            // 3. ทางปกติสำหรับ npm และอื่นๆ
            console.log(`  ->  Using standard template strategy`);
            const templates = this.selectTemplates(projectType, features);
            for (const template of templates) {
                const templateButtons = this.templateLibrary[template];
                if (templateButtons) {
                    buttons.push(...this.customizeButtons(templateButtons.buttons, projectInfo, features));
                }
            }
        }
        // --- จบส่วนตรรกะ ---

        // เพิ่มปุ่มพิเศษตามฟีเจอร์ (เฉพาะโปรเจคธรรมดา)
        if (!features.hasBatchRunner && projectType !== 'executable_project') {
            buttons.push(...this.generateConditionalButtons(features, projectInfo));
        }

        // เพิ่มปุ่มยูทิลิตี้พื้นฐาน
        buttons.push(...this.generateUtilityButtons(projectInfo));

        //  เพิ่มข้อมูลภาพตัวอย่างในปุ่มทุกปุ่ม
        buttons = buttons.map(button => ({
            ...button,
            previewImage: previewImage, // เพิ่มภาพตัวอย่าง
            projectPreview: previewImage // เก็บ reference เพิ่มเติม
        }));

        // ลงทะเบียนปุ่ม
        this.buttonRegistry.set(name, {
            projectInfo,
            buttons,
            previewImage, //  เก็บ previewImage ใน registry
            generated: new Date().toISOString()
        });

        console.log(` Generated ${buttons.length} buttons for ${name} with preview: ${previewImage || 'none'}`);
        return buttons;
    }

    //  เลือกเทมเพลตตามประเภทและฟีเจอร์
    selectTemplates(projectType, features) {
        const templates = [];

        switch (projectType) {
            case 'node':
                templates.push('node-basic');
                if (features.hasLinter || features.hasTests || features.hasTypeScript) {
                    templates.push('node-advanced');
                }
                break;

            case 'python':
                templates.push('python-basic');
                if (features.hasFlask || features.hasDjango || features.hasJupyter) {
                    templates.push('python-web');
                }
                break;

            case 'html':
                templates.push('web-basic');
                break;

            case 'studio':
                templates.push('studio');
                break;

            //  เพิ่มการรองรับ executable และ batch projects
            case 'executable_project':
                templates.push('executable-runner');
                break;

            case 'batch_project':
                templates.push('batch-runner');
                break;

            default:
                templates.push('utility');
                break;
        }

        return templates;
    }

    //  ปรับแต่งปุ่มตามโปรเจค
    customizeButtons(templateButtons, projectInfo, features) {
        return templateButtons.map(btn => ({
            ...btn,
            name: this.translate(btn.nameKey), // แปลชื่อปุ่ม
            projectName: projectInfo.name,
            projectPath: projectInfo.path,
            projectType: projectInfo.type,
            enabled: this.checkButtonCompatibility(btn, features),
            tooltip: `${this.translate(btn.nameKey)} for ${projectInfo.name}`,
            lastUsed: null
        }));
    }

    //  สร้างปุ่มแบบมีเงื่อนไข
    generateConditionalButtons(features, projectInfo) {
        const conditionalButtons = [];

        // Electron specific buttons - ลบปุ่ม Dev ออก
        // if (features.hasElectron) {
        //     conditionalButtons.push({
        //         id: 'electron-dev',
        //         name: 'Electron Dev',
        //         command: 'electron-dev',
        //         icon: '',
        //         color: '#9F7AEA',
        //         category: 'electron',
        //         projectName: projectInfo.name,
        //         projectPath: projectInfo.path,
        //         enabled: true
        //     });
        // }

        // TypeScript specific buttons
        if (features.hasTypeScript) {
            conditionalButtons.push({
                id: 'tsc-check',
                nameKey: 'npm-build', // ใช้ key ที่เป็น static
                name: this.translate(features.hasTypeScript ? 'npm-build' : 'npm-lint'),
                //  FIX: เปลี่ยน command จาก 'npx tsc --noEmit' เป็น 'tsc-check'
                command: 'tsc-check',
                icon: '',
                color: '#3182CE',
                category: 'typescript',
                projectName: projectInfo.name,
                projectPath: projectInfo.path,
                enabled: true
            });
        }

        return conditionalButtons;
    }

    //  สร้างปุ่มยูทิลิตี้
    generateUtilityButtons(projectInfo) {
        const utilityTemplate = this.templateLibrary['utility'];
        return this.customizeButtons(utilityTemplate.buttons, projectInfo, {});
    }

    //  ตรวจสอบความเข้ากันได้ของปุ่ม
    checkButtonCompatibility(button, features) {
        // ตรวจสอบเงื่อนไขเฉพาะ
        if (button.requires) {
            return button.requires.every(req => features[req]);
        }

        // ปุ่มพื้นฐานใช้ได้เสมอ
        return true;
    }

    //  ปรับแต่งปุ่มสำหรับ Batch Scripts (เวอร์ชันแก้ไข)
    customizeBatchButtons(batchButtons, projectInfo) {
        const fs = require('fs');
        const path = require('path');
        
        const { path: projectPath, name } = projectInfo;
        const customizedButtons = [];

        try {
            const files = fs.readdirSync(projectPath);
            const batchFiles = files.filter(file => 
                file.endsWith('.bat') || file.endsWith('.cmd')
            );

            console.log(`  -> Found ${batchFiles.length} batch files: ${batchFiles.join(', ')}`);

            // ถ้าไม่เจอไฟล์ batch เลย ก็ไม่ต้องสร้างปุ่ม
            if (batchFiles.length === 0) return [];

            // ใช้ไฟล์ .bat แรกที่เจอ หรือหาตัวที่ชื่อตรงกับโฟลเดอร์
            const targetBatch = batchFiles.find(file => 
                file.toLowerCase().includes(name.toLowerCase())
            ) || batchFiles[0];

            for (const button of batchButtons) {
                const customButton = { ...button };

                //  **จุดแก้ไข:** ให้ command เป็น action name ไม่ใช่ชื่อไฟล์
                if (button.id === 'run-batch') {
                    customButton.command = 'run-batch'; // <--- แก้ไขตรงนี้
                    customButton.name = `Run ${path.parse(targetBatch).name}`;
                    customButton.tooltip = `Execute ${targetBatch}`;
                } else if (button.id === 'edit-batch') {
                    customButton.command = 'edit-batch'; // <--- แก้ไขตรงนี้
                    customButton.name = `Edit ${path.parse(targetBatch).name}`;
                    customButton.tooltip = `Edit ${targetBatch} in Notepad`;
                }

                if (customButton.command) {
                    customizedButtons.push(customButton);
                }
            }

            console.log(`  -> Customized ${customizedButtons.length} batch buttons`);
            return customizedButtons;

        } catch (error) {
            console.log(`  -> Error customizing batch buttons: ${error.message}`);
            return [];
        }
    }

    //  ปรับแต่งปุ่มสำหรับ Executable Files (เวอร์ชันแก้ไข)
    customizeExecutableButtons(exeButtons, projectInfo) {
        const fs = require('fs');
        const path = require('path');
        
        const { path: projectPath, name } = projectInfo;
        const customizedButtons = [];

        try {
            const files = fs.readdirSync(projectPath);
            const exeFiles = files.filter(file => file.endsWith('.exe'));

            console.log(`  -> Found ${exeFiles.length} executable files: ${exeFiles.join(', ')}`);
            
            // ถ้าไม่เจอไฟล์ .exe เลย ก็ไม่ต้องสร้างปุ่ม
            if (exeFiles.length === 0) return [];

            // ใช้ไฟล์ .exe แรกที่เจอ หรือหาตัวที่ชื่อตรงกับโฟลเดอร์
            const targetExe = exeFiles.find(file => 
                file.toLowerCase().includes(name.toLowerCase())
            ) || exeFiles[0];

            for (const button of exeButtons) {
                const customButton = { ...button };

                //  **จุดแก้ไข:** ให้ command เป็น action name ที่ Gateway รู้จัก
                if (button.id === 'launch-exe') {
                    customButton.command = 'launch-exe'; // <--- แก้ไขตรงนี้
                    customButton.name = `Launch ${path.parse(targetExe).name}`;
                    customButton.tooltip = `Execute ${targetExe}`;
                } else if (button.id === 'run-as-admin') {
                    customButton.command = 'run-as-admin'; // <--- แก้ไขตรงนี้
                    customButton.name = `Admin ${path.parse(targetExe).name}`;
                    customButton.tooltip = `Run ${targetExe} as Administrator`;
                }

                if (customButton.command) {
                    customizedButtons.push(customButton);
                }
            }

            console.log(`  -> Customized ${customizedButtons.length} executable buttons`);
            return customizedButtons;

        } catch (error) {
            console.log(`  -> Error customizing executable buttons: ${error.message}`);
            return [];
        }
    }

    //  สร้าง HTML สำหรับปุ่ม
    generateButtonHTML(button) {
        const hotkey = button.hotkey ? `title="${button.tooltip || button.name} (${button.hotkey})"` : `title="${button.tooltip || button.name}"`;
        
        //  เพิ่ม preview image ถ้ามี
        const previewImageHTML = button.previewImage ? 
            `<div class="button-preview" style="background-image: url('${button.previewImage}'); background-size: cover; background-position: center; width: 40px; height: 30px; border-radius: 4px; margin-right: 8px;"></div>` : '';
        
        return `
            <button 
                class="project-button" 
                data-button-id="${button.id}"
                data-project="${button.projectName}"
                data-command="${button.command}"
                style="background-color: ${button.color || '#718096'}; margin: 4px; padding: 8px 12px; border: none; border-radius: 6px; color: white; cursor: pointer; font-size: 14px; display: inline-flex; align-items: center; gap: 6px;"
                ${hotkey}
                ${!button.enabled ? 'disabled' : ''}
            >
                ${previewImageHTML}
                <span>${button.icon || ''}</span>
                <span>${button.name}</span>
            </button>
        `;
    }

    //  สร้างภาพตัวอย่างแบบ SVG สำหรับปุ่ม
    generateButtonPreviewSVG(projectType, projectName) {
        const previewConfigs = {
            'executable_project': {
                color: '#4A5568',
                icon: '',
                label: 'EXE'
            },
            'batch_project': {
                color: '#38A169',
                icon: '',
                label: 'BAT'
            },
            'node': {
                color: '#68D391',
                icon: '',
                label: 'NODE'
            },
            'python': {
                color: '#4FD1C7',
                icon: '',
                label: 'PY'
            },
            'html': {
                color: '#90CDF4',
                icon: '',
                label: 'WEB'
            },
            'default': {
                color: '#718096',
                icon: '',
                label: 'PLUGIN'
            }
        };

        const config = previewConfigs[projectType] || previewConfigs['default'];
        
        const svgContent = `
            <svg width="100" height="80" xmlns="http://www.w3.org/2000/svg">
                <rect width="100" height="80" fill="${config.color}" rx="4"/>
                <text x="50" y="35" font-family="Arial" font-size="20" fill="white" text-anchor="middle">${config.icon}</text>
                <text x="50" y="55" font-family="Arial" font-size="10" fill="#E2E8F0" text-anchor="middle">${config.label}</text>
                <text x="50" y="70" font-family="Arial" font-size="8" fill="#CBD5E0" text-anchor="middle">${projectName.substring(0, 12)}</text>
            </svg>
        `;

        return `data:image/svg+xml;base64,${Buffer.from(svgContent).toString('base64')}`;
    }

    //  สร้างภาพตัวอย่างสำหรับปุ่มเก่าที่ยังไม่มี
    generateMissingPreviews() {
        const updated = [];
        
        for (const [projectName, projectData] of this.buttonRegistry.entries()) {
            if (!projectData.previewImage) {
                const { projectInfo } = projectData;
                const previewImage = this.generateButtonPreviewSVG(projectInfo.type, projectInfo.name);
                
                // อัปเดตข้อมูลใน registry
                projectData.previewImage = previewImage;
                projectData.projectInfo.previewImage = previewImage;
                
                // อัปเดตปุ่มทั้งหมด
                projectData.buttons = projectData.buttons.map(button => ({
                    ...button,
                    previewImage: previewImage,
                    projectPreview: previewImage
                }));
                
                updated.push(projectName);
                console.log(` Generated missing preview for: ${projectName}`);
            }
        }
        
        if (updated.length > 0) {
            console.log(` Updated ${updated.length} projects with missing previews`);
        }
        
        return updated;
    }

    //  สร้าง HTML การ์ดโปรเจคแบบเต็ม (รวมภาพตัวอย่าง)
    generateProjectCardHTML(projectData) {
        const { projectInfo, buttons, previewImage } = projectData;
        
        const cardPreviewImage = previewImage || this.generateButtonPreviewSVG(projectInfo.type, projectInfo.name);
        
        const buttonsHTML = buttons.map(button => this.generateButtonHTML(button)).join('');
        
        return `
            <div class="project-card" data-project="${projectInfo.name}">
                <div class="project-header">
                    <div class="project-preview">
                        <img src="${cardPreviewImage}" alt="Preview for ${projectInfo.name}" class="preview-image">
                    </div>
                    <div class="project-info">
                        <h3 class="project-title">${projectInfo.name}</h3>
                        <p class="project-type">${projectInfo.type}</p>
                        <p class="project-path">${projectInfo.path}</p>
                    </div>
                </div>
                <div class="project-buttons">
                    ${buttonsHTML}
                </div>
            </div>
        `;
    }

    //  ดึงข้อมูลปุ่มทั้งหมด
    getAllButtons() {
        return Array.from(this.buttonRegistry.values());
    }

    //  ดึงปุ่มสำหรับโปรเจคเฉพาะ
    getProjectButtons(projectName) {
        const projectData = this.buttonRegistry.get(projectName);
        return projectData ? projectData.buttons : [];
    }

    //  รีเซ็ตระบบปุ่ม
    reset() {
        this.buttonRegistry.clear();
        console.log(' Button registry reset');
    }
}

module.exports = ButtonGenerator;