File size: 128,239 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
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
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433

        /**
         *  CHAHUADEV FRAMEWORK - ระบบจัดการปลั๊กอินอัจฉริยะ
         * =========================================================
         * 
         *  ภาพรวมระบบ:
         * - ระบบจัดการปลั๊กอิน HTML, Node.js, Python, Java
         * - ตัวอย่างการใช้งาง และการ build แบบอัตโนมัติ
         * - การตรวจสอบ Error และ Debug แบบขั้นสูง
         * - UI ที่ทันสมัยและใช้งานง่าย
         * 
         *  การเชื่อมโยง API หลัก:
         * - window.electronAPI (preload.js) -> Main Process (main.js)
         * - validation_gateway.js -> Security & Command Validation
         * 
         *  ฟังก์ชันหลัก:
         * 1. addTerminalLine() -> แสดงข้อความใน Log Viewer
         * 2. scanAndRenderPlugins() -> สแกนและแสดงปลั๊กอิน
         * 3. Build Functions -> การ Build และ Deploy ปลั๊กอิน
         * 4. Animation & Effects -> เอฟเฟกต์ UI ต่างๆ
         * 5. Plugin Management -> จัดการปลั๊กอินและโปรเจกต์
         */
        
        // --- เพิ่มส่วนนี้เข้าไป ---
        // รายการคำสั่งของระบบที่อนุญาตให้รันได้ (ปลอดภัยและมีประโยชน์)
        const safeExternalCommands = new Set([
            'ping',       // สำหรับทดสอบการเชื่อมต่อเครือข่าย
            'tracert',    // สำหรับติดตามเส้นทางเครือข่าย
            'ipconfig',   // (สำหรับ Windows) สำหรับดูข้อมูล IP Address
            'ifconfig',   // (สำหรับ Mac/Linux) สำหรับดูข้อมูล IP Address
            'getmac',     // สำหรับดู MAC Address ของเครื่อง
            'node',       // อนุญาตให้รัน node เช่น node -v
            'npm'         // อนุญาตให้รัน npm เช่น npm -v
        ]);
        // --- จบส่วนที่เพิ่ม ---

        const logViewer = document.getElementById('log-viewer');
        const pluginContainer = document.getElementById('plugin-container');

        // --- CORE FUNCTIONS ---
        
        //  [เวอร์ชันใหม่] ฟังก์ชันสำหรับเขียน Log ที่เข้ากับ debugger.html 
        /**
         * ฟังก์ชันแสดงข้อความใน Log Viewer หลัก
         * 
         * @function addTerminalLine
         * @description แสดงข้อความใน Log Viewer พร้อม timestamp และสีที่เหมาะสม
         * @param {string} text - ข้อความที่ต้องการแสดง
         * @param {string} [type='info'] - ประเภทของข้อความ (info, success, error, warning, command)
         * 
         * @example
         * addTerminalLine('ระบบเริ่มทำงานแล้ว', 'success');
         * addTerminalLine('เกิดข้อผิดพลาด', 'error');
         * 
         * @dependencies
         * - logViewer (DOM element) -> #log-viewer
         * 
         * @calledBy
         * - scanAndRenderPlugins() -> แสดงผลการสแกนปลั๊กอิน
         * - runGeneratorAndRefresh() -> แสดงผลการ build
         * - openDebugWindow() -> แสดงสถานะการเปิด debug
         * - DOMContentLoaded event -> แสดงข้อความเริ่มต้น
         * 
         * @sideEffects
         * - เพิ่ม DOM element ใหม่ใน #log-viewer
         * - เลื่อน scroll ไปบรรทัดล่าสุดอัตโนมัติ
         */
        const addTerminalLine = (text, type = 'info') => {
            if (!logViewer) return;

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

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

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

        //  เพิ่มฟังก์ชันนี้สำหรับปุ่ม "เปิดหน้าต่าง Debug"
        /**
         * ฟังก์ชันเปิดหน้าต่าง Debug Window
         * 
         * @function openDebugWindow
         * @async
         * @description เปิดหน้าต่างใหม่สำหรับ Debug และตรวจสอบ Error
         * 
         * @returns {Promise<void>}
         * 
         * @dependencies
         * - window.electronAPI.openDebugWindow() -> API จาก preload.js
         * 
         * @calledBy
         * - onclick ของปุ่ม Debug ใน HTML
         * - คีย์ลัด Ctrl+D (Developer mode เท่านั้น)
         * 
         * @calls
         * - addTerminalLine() -> แสดงสถานะการเปิด debug
         * 
         * @throws {Error} เมื่อไม่สามารถเปิดหน้าต่าง debug ได้
         */
        async function openDebugWindow() {
            addTerminalLine(' กำลังเปิดหน้าต่าง Debug...', 'command');
            try {
                // เรียก API ที่เราจะสร้างในขั้นตอนต่อไป
                await window.electronAPI.openDebugWindow();
                addTerminalLine(' เปิดหน้าต่าง Debug สำเร็จ', 'success');
            } catch (error) {
                addTerminalLine(` ไม่สามารถเปิดหน้าต่าง Debug ได้: ${error.message}`, 'error');
            }
        }

        // Keyboard support (Escape key + Resize)
        document.addEventListener('keydown', (event) => {
            if (event.key === 'Escape') {
                // Stop resize if active
                if (window.resizeController && window.resizeController.isResizing) {
                    window.resizeController.stopResize();
                }
            }
        });

        /**
         * ฟังก์ชันคัดลอก Machine ID
         * 
         * @function copyMachineID
         * @async
         * @param {string} machineID - รหัสเครื่อง
         * @description คัดลอก Machine ID ไปยัง Clipboard
         * 
         * @returns {Promise<void>}
         * 
         * @dependencies
         * - navigator.clipboard API -> Clipboard access
         * 
         * @calledBy
         * - UI elements -> ปุ่ม copy machine ID
         * 
         * @calls addTerminalLine() -> แสดงผลการคัดลอก
         * 
         * @sideEffects
         * - คัดลอกข้อมูลไป clipboard
         * - แสดงข้อความยืนยัน
         */
        async function copyMachineID(machineID) {
            try {
                await navigator.clipboard.writeText(machineID);
                addTerminalLine(` คัดลอกรหัสเครื่องแล้ว: ${machineID}`, 'success');
            } catch (error) {
                addTerminalLine(` ไม่สามารถคัดลอกได้: ${error.message}`, 'error');
            }
        }

        /**
         * ฟังก์ชันสแกนและแสดงรายการปลั๊กอิน
         * 
         * @function scanAndRenderPlugins
         * @async
         * @description สแกนหาปลั๊กอินในระบบและแสดงผลใน UI
         * 
         * @returns {Promise<void>}
         * 
         * @dependencies
         * - window.electronAPI.executeCommand() -> API จาก preload.js
         * - pluginContainer (DOM) -> #plugin-container
         * 
         * @calledBy
         * - DOMContentLoaded event -> โหลดเริ่มต้น
         * - runGeneratorAndRefresh() -> หลังจาก build เสร็จ
         * - ปุ่ม Refresh ต่างๆ
         * 
         * @calls
         * - addTerminalLine() -> แสดงสถานะการสแกน
         * - createPluginButtons() -> สร้างปุ่มสำหรับแต่ละปลั๊กอิน
         * 
         * @throws {Error} เมื่อไม่สามารถสแกนปลั๊กอินได้
         * 
         * @sideEffects
         * - เปลี่ยน innerHTML ของ #plugin-container
         * - แสดงข้อความใน Log Viewer
         */
        async function scanAndRenderPlugins() {
            addTerminalLine(' กำลังสแกนปลั๊กอิน...', 'command');
            
            // แสดง loading animation
            showLoadingAnimation(pluginContainer, 'กำลังสแกนปลั๊กอิน');

            //  เรียกใช้ API ที่ถูกต้องและมีอยู่จริงใน main.js
            // preload.js ได้เตรียม window.electronAPI.plugins.getAll() ไว้ให้แล้ว
            const result = await window.electronAPI.plugins.getAll(); 
            
            console.log('--- Data from Main Process (get-available-plugins) ---', result);

            if (result.success && result.plugins) {
                pluginContainer.innerHTML = '<div class="plugin-grid"></div>';
                const grid = pluginContainer.querySelector('.plugin-grid');
                const plugins = result.plugins;

                if (plugins.length === 0) {
                    grid.innerHTML = `<div class="loading">ไม่พบปลั๊กอินหรือโปรเจกต์ที่ทำงานได้</div>`;
                    addTerminalLine(' ไม่พบโปรเจกต์ที่สามารถสร้างปุ่มการทำงานได้', 'info');
                } else {
                    // เพิ่ม plugins ทีละตัวพร้อม animation delay
                    plugins.forEach((pluginData, index) => {
                        setTimeout(() => {
                            const card = document.createElement('div');
                            card.className = 'plugin-card';
                            card.style.animationDelay = `${index * 0.1}s`;
                            card.innerHTML = `
                                ${pluginData.previewImage ? `<img src="${pluginData.previewImage}" class="plugin-preview-image" alt="Preview for ${pluginData.name}">` : ''}
                                <h3>${getIconForType(pluginData)} ${pluginData.name}</h3>
                                <p>${pluginData.description || `ประเภท: ${pluginData.type}`}</p>
                                ${pluginData.debugInfo ? `
                                    <div class="debug-info">
                                        <div class="debug-stats">
                                            <span class="stat-files"> ${pluginData.debugInfo.totalFiles || 0} files</span>
                                            <span class="stat-issues ${pluginData.debugInfo.errors > 0 ? 'has-errors' : ''}">
                                                ${pluginData.debugInfo.errors || 0} errors, ${pluginData.debugInfo.warnings || 0} warnings
                                            </span>
                                        </div>
                                    </div>
                                ` : ''}
                                <div class="plugin-buttons">
                                    ${createPluginButtons(pluginData)}
                                </div>
                            `;
                            grid.appendChild(card);
                        }, index * 100);
                    });
                    
                    // แสดงผลลัพธ์หลังจาก animations เสร็จ
                    setTimeout(() => {
                        addTerminalLine(` สแกนเสร็จสิ้น พบ ${plugins.length} โปรเจกต์ที่พร้อมใช้งาน`, 'success');
                        showNotification(` พบ ${plugins.length} ปลั๊กอินที่พร้อมใช้งาน!`, 'success');
                    }, (plugins.length * 100) + 200);
                }
            } else {
                pluginContainer.innerHTML = `<div class="loading">เกิดข้อผิดพลาดในการโหลดปลั๊กอิน</div>`;
                addTerminalLine(` ข้อผิดพลาดในการสแกนปลั๊กอิน: ${result.error || 'ไม่ได้รับข้อมูลจาก Main Process'}`, 'error');
                showNotification(' เกิดข้อผิดพลาดในการสแกนปลั๊กอิน', 'error');
            }
        }

        //  Enhanced Plugin Scan with Debug Info
        /**
         * ฟังก์ชันสแกนปลั๊กอินพร้อมข้อมูล Debug
         * 
         * @function scanAndRenderPluginsWithDebug
         * @async
         * @description สแกนปลั๊กอินและแสดงข้อมูล Debug เพิ่มเติม
         * 
         * @returns {Promise<void>}
         * 
         * @dependencies
         * - window.electronAPI.executeCommand() -> API การสแกนแบบ Debug
         * 
         * @calledBy
         * - Developer mode functions
         * - Debug buttons
         * 
         * @calls
         * - addTerminalLine() -> แสดงข้อมูล Debug
         * - createPluginButtons() -> สร้าง UI ปลั๊กอิน
         * 
         * @sideEffects
         * - แสดงข้อมูล Debug ใน Log Viewer
         * - อัพเดต Plugin Container
         */
        async function scanAndRenderPluginsWithDebug() {
            addTerminalLine(' กำลังสแกนปลั๊กอินพร้อมข้อมูล Debug...', 'command');
            
            // แสดง loading animation
            showLoadingAnimation(pluginContainer, 'กำลังวิเคราะห์ปลั๊กอิน');

            try {
                // ใช้ IPC handler ที่เราสร้างใหม่ - แก้ไขใช้ API ที่ถูกต้อง
                const result = await window.electronAPI.projectInspector.scanWithDebug();
                
                console.log('--- Enhanced Scan Result ---', result);

                if (result.success && result.plugins) {
                    pluginContainer.innerHTML = '<div class="plugin-grid"></div>';
                    const grid = pluginContainer.querySelector('.plugin-grid');
                    const plugins = result.plugins;

                    if (plugins.length === 0) {
                        grid.innerHTML = `<div class="loading">ไม่พบปลั๊กอินหรือโปรเจกต์ที่ทำงานได้</div>`;
                        addTerminalLine(' ไม่พบโปรเจกต์ที่สามารถสร้างปุ่มการทำงานได้', 'info');
                    } else {
                        let totalErrors = 0;
                        let totalWarnings = 0;
                        
                        // เพิ่ม plugins ทีละตัวพร้อม animation delay
                        plugins.forEach((pluginData, index) => {
                            setTimeout(() => {
                                const card = document.createElement('div');
                                card.className = 'plugin-card';
                                card.style.animationDelay = `${index * 0.1}s`;
                                card.innerHTML = `
                                    ${pluginData.previewImage ? `<img src="${pluginData.previewImage}" class="plugin-preview-image" alt="Preview for ${pluginData.name}">` : ''}
                                    <h3>${getIconForType(pluginData)} ${pluginData.name}</h3>
                                    <p>${pluginData.description || `ประเภท: ${pluginData.type}`}</p>
                                    ${pluginData.debugInfo ? `
                                        <div class="debug-info">
                                            <div class="debug-stats">
                                                <span class="stat-files"> ${pluginData.debugInfo.totalFiles || 0} files</span>
                                                <span class="stat-issues ${pluginData.debugInfo.errors > 0 ? 'has-errors' : ''}">
                                                    ${pluginData.debugInfo.errors || 0} errors, ${pluginData.debugInfo.warnings || 0} warnings
                                                </span>
                                            </div>
                                        </div>
                                    ` : ''}
                                    <div class="plugin-buttons">
                                        ${createPluginButtons(pluginData)}
                                    </div>
                                `;
                                grid.appendChild(card);
                                
                                // รวมสถิติ
                                if (pluginData.debugInfo) {
                                    totalErrors += pluginData.debugInfo.errors || 0;
                                    totalWarnings += pluginData.debugInfo.warnings || 0;
                                }
                            }, index * 100);
                        });
                        
                        // แสดงผลลัพธ์หลังจาก animations เสร็จ
                        setTimeout(() => {
                            addTerminalLine(` Enhanced scan เสร็จสิ้น: ${plugins.length} projects`, 'success');
                            addTerminalLine(` พบปัญหา: ${totalErrors} errors, ${totalWarnings} warnings`, 
                                totalErrors > 0 ? 'error' : 'info');
                            showNotification(` สแกน ${plugins.length} ปลั๊กอิน พร้อมข้อมูล Debug!`, 'success');
                        }, (plugins.length * 100) + 200);
                    }
                } else {
                    pluginContainer.innerHTML = `<div class="loading">เกิดข้อผิดพลาดในการสแกน Debug</div>`;
                    addTerminalLine(` ข้อผิดพลาดในการสแกน Debug: ${result.error || 'ไม่ได้รับข้อมูลจาก Main Process'}`, 'error');
                    showNotification(' เกิดข้อผิดพลาดในการสแกน Debug', 'error');
                }
            } catch (error) {
                console.error('Enhanced scan error:', error);
                pluginContainer.innerHTML = `<div class="loading">เกิดข้อผิดพลาดในการสแกน Debug</div>`;
                addTerminalLine(` Enhanced scan failed: ${error.message}`, 'error');
                showNotification(' เกิดข้อผิดพลาดในการสแกน Debug', 'error');
            }
        }

        //  ฟังก์ชันใหม่สำหรับรัน Generator และ Refresh
        /**
         * ฟังก์ชันรัน Generator และ Refresh ปลั๊กอิน
         * 
         * @function runGeneratorAndRefresh
         * @async
         * @description รัน Plugin Generator เพื่อสร้างไฟล์ manifest และ refresh รายการปลั๊กอิน
         * 
         * @returns {Promise<void>}
         * 
         * @dependencies
         * - window.electronAPI.executeCommand() -> API รัน generator
         * 
         * @calledBy
         * - ปุ่ม "สแกน & สร้าง" ใน UI
         * - คีย์ลัด Ctrl+R (Developer mode)
         * 
         * @calls
         * - addTerminalLine() -> แสดงสถานะการทำงาน
         * - scanAndRenderPlugins() -> อัพเดตรายการปลั๊กอิน
         * 
         * @throws {Error} เมื่อ Generator ทำงานไม่สำเร็จ
         * 
         * @sideEffects
         * - สร้างไฟล์ manifest.json สำหรับปลั๊กอิน
         * - อัพเดต UI รายการปลั๊กอิน
         * - แสดงข้อความสถานะใน Log
         */
        async function runGeneratorAndRefresh() {
            addTerminalLine(' กำลังสั่งให้ระบบสแกนหาปลั๊กอินใหม่และสร้าง Manifest...', 'command');
            
            // แสดง loading ใน plugin container
            showLoadingAnimation(pluginContainer, 'กำลังสร้าง Manifest');
            
            try {
                const result = await window.electronAPI.runManifestGenerator();
                if (result.success) {
                    addTerminalLine(' สร้าง Manifest สำเร็จ! กำลังโหลดรายการปลั๊กอินใหม่...', 'success');
                    showNotification(' สร้าง Manifest สำเร็จ!', 'success');
                    
                    // โหลดรายการปลั๊กอินใหม่หลังจากสร้างเสร็จ
                    setTimeout(async () => {
                        await scanAndRenderPlugins();
                    }, 500);
                } else {
                    addTerminalLine(` เกิดข้อผิดพลาดในการสร้าง Manifest: ${result.error}`, 'error');
                    showNotification(' เกิดข้อผิดพลาดในการสร้าง Manifest', 'error');
                    pluginContainer.innerHTML = `<div class="loading">เกิดข้อผิดพลาดในการสร้าง Manifest</div>`;
                }
            } catch (error) {
                addTerminalLine(` ข้อผิดพลาด IPC ร้ายแรง: ${error.message}`, 'error');
                showNotification(' ข้อผิดพลาด IPC ร้ายแรง', 'error');
                pluginContainer.innerHTML = `<div class="loading">เกิดข้อผิดพลาดร้ายแรง</div>`;
            }
        }

        //  ฟังก์ชันสำหรับรัน Manifest Generator เท่านั้น
        /**
         * ฟังก์ชันสร้างเฉพาะไฟล์ Manifest
         * 
         * @function runGenerateManifestOnly
         * @async
         * @description รัน Generator เพื่อสร้างเฉพาะไฟล์ manifest.json
         * 
         * @returns {Promise<void>}
         * 
         * @dependencies
         * - window.electronAPI.executeCommand() -> API รัน manifest generator
         * 
         * @calledBy
         * - ปุ่ม "สร้าง Manifest" ใน UI
         * 
         * @calls addTerminalLine() -> แสดงสถานะ
         * 
         * @sideEffects
         * - สร้างไฟล์ manifest.json
         * - แสดงข้อความใน Log
         */
        async function runGenerateManifestOnly() {
            addTerminalLine(' กำลังรันตัวสร้าง Manifest Files...', 'command');
            try {
                const result = await window.electronAPI.runManifestGenerator();
                if (result.success) {
                    addTerminalLine(' สร้าง Manifest Files สำเร็จ!', 'success');
                    addTerminalLine(` ผลลัพธ์:`, 'info');
                    addTerminalLine(result.output, 'stdout');
                } else {
                    addTerminalLine(` เกิดข้อผิดพลาดในการสร้าง Manifest: ${result.error}`, 'error');
                }
            } catch (error) {
                addTerminalLine(` ข้อผิดพลาด IPC ร้ายแรง: ${error.message}`, 'error');
            }
        }

        //  ฟังก์ชันเปิดโฟลเดอร์ปลั๊กอิน (NEW)
        /**
         * ฟังก์ชันเปิดโฟลเดอร์ Plugins
         * 
         * @function openPluginsFolder
         * @async
         * @description เปิด File Explorer ไปยังโฟลเดอร์ plugins
         * 
         * @returns {Promise<void>}
         * 
         * @dependencies
         * - window.electronAPI.executeCommand() -> API เปิดโฟลเดอร์
         * 
         * @calledBy ปุ่ม "เปิดโฟลเดอร์" ใน UI
         * @calls addTerminalLine() -> แสดงสถานะ
         * 
         * @sideEffects
         * - เปิด File Explorer/Finder
         * - แสดงข้อความใน Log
         */
        async function openPluginsFolder() {
            addTerminalLine(' กำลังเปิดโฟลเดอร์ปลั๊กอิน...', 'command');
            try {
                const result = await window.electronAPI.openPluginsFolder();
                if (result.success) {
                    addTerminalLine(' เปิดโฟลเดอร์ปลั๊กอินใน File Explorer แล้ว', 'success');
                    addTerminalLine(` ตำแหน่ง: ${result.path}`, 'info');
                    addTerminalLine(' คุณสามารถวางไฟล์ปลั๊กอินของคุณในโฟลเดอร์นี้แล้วกดปุ่ม " สแกนหาปลั๊กอินใหม่"', 'info');
                    showNotification(' เปิดโฟลเดอร์ปลั๊กอินแล้ว!', 'success');
                } else {
                    addTerminalLine(` ไม่สามารถเปิดโฟลเดอร์ปลั๊กอินได้: ${result.error}`, 'error');
                    showNotification(' ไม่สามารถเปิดโฟลเดอร์ปลั๊กอินได้', 'error');
                }
            } catch (error) {
                addTerminalLine(` ข้อผิดพลาด IPC: ${error.message}`, 'error');
                showNotification(' ข้อผิดพลาด IPC', 'error');
            }
        }

        //  ฟังก์ชัน Build App (MSI/EXE) - NEW
        /**
         * ฟังก์ชันเริ่มกระบวนการ Build
         * 
         * @function startBuildProcess
         * @async
         * @description เริ่มกระบวนการ build ปลั๊กอินพร้อม UI animation
         * 
         * @returns {Promise<void>}
         * 
         * @dependencies
         * - window.electronAPI.executeCommand() -> API build process
         * 
         * @calledBy
         * - ปุ่ม Build ของแต่ละปลั๊กอิน
         * - createPluginButtons() -> สร้างปุ่ม build
         * 
         * @calls
         * - addTerminalLine() -> แสดงสถานะ build
         * - onBuildComplete() -> เมื่อ build เสร็จสิ้น
         * 
         * @sideEffects
         * - แสดง build animation
         * - สร้างไฟล์ output
         * - อัพเดต UI
         */
        async function startBuildProcess() {
            addTerminalLine(' กำลังเริ่มต้นกระบวนการ Build แอปพลิเคชัน...', 'command');
            addTerminalLine(' คำสั่ง: npx electron-builder --win --x64', 'command');
            addTerminalLine(' กรุณารอสักครู่ กระบวนการนี้อาจใช้เวลาหลายนาที...', 'info');
            addTerminalLine(' การ Build จะสร้างไฟล์ MSI และ EXE สำหรับติดตั้งบน Windows', 'info');
            
            // แสดงการแจ้งเตือนและอนิเมชั่น
            showNotification(' เริ่มต้น Build Process...', 'info');
            
            // แสดง loading animation แบบพิเศษสำหรับ build process
            const buildStatusDiv = document.createElement('div');
            buildStatusDiv.id = 'build-status';
            buildStatusDiv.style.cssText = `
                background: linear-gradient(135deg, #fd7e14, #e76500);
                color: white;
                padding: 15px;
                margin: 10px 0;
                border-radius: 8px;
                border-left: 4px solid #fff;
                animation: pulse 2s infinite;
            `;
            buildStatusDiv.innerHTML = `
                <div style="display: flex; align-items: center; justify-content: center;">
                    <div style="
                        width: 20px;
                        height: 20px;
                        border: 3px solid rgba(255,255,255,0.3);
                        border-top: 3px solid white;
                        border-radius: 50%;
                        animation: spin 1s linear infinite;
                        margin-right: 10px;
                    "></div>
                    <span> กำลัง Build แอปพลิเคชัน...</span>
                </div>
            `;
            
            // เพิ่ม build status
            const licenseStatus = document.getElementById('license-status');
            licenseStatus.parentNode.insertBefore(buildStatusDiv, licenseStatus.nextSibling);
            
            try {
                const result = await window.electronAPI.startBuild();
                if (!result.success) {
                    addTerminalLine(` ไม่สามารถเริ่ม Build ได้: ${result.error}`, 'error');
                    showNotification(' ไม่สามารถเริ่ม Build ได้', 'error');
                    
                    // ลบ build status
                    buildStatusDiv.remove();
                } else {
                    addTerminalLine(' เริ่มกระบวนการ Build สำเร็จ!', 'success');
                    
                    // เปลี่ยน build status เป็น running
                    buildStatusDiv.innerHTML = `
                        <div style="display: flex; align-items: center; justify-content: center;">
                            <div style="
                                width: 20px;
                                height: 20px;
                                border: 3px solid rgba(255,255,255,0.3);
                                border-top: 3px solid white;
                                border-radius: 50%;
                                animation: spin 1s linear infinite;
                                margin-right: 10px;
                            "></div>
                            <span> กำลังดำเนินการ Build... (ตรวจสอบ Log ด้านล่าง)</span>
                        </div>
                    `;
                }
            } catch (error) {
                addTerminalLine(` เกิดข้อผิดพลาดร้ายแรง: ${error.message}`, 'error');
                showNotification(' เกิดข้อผิดพลาดร้ายแรง', 'error');
                
                // ลบ build status
                buildStatusDiv.remove();
            }
        }
        
        //  ฟังก์ชันจัดการเมื่อ Build เสร็จสิ้น
        /**
         * ฟังก์ชันที่ทำงานเมื่อ Build เสร็จสิ้น
         * 
         * @function onBuildComplete
         * @param {boolean} success - สถานะความสำเร็จของการ build
         * @description จัดการ UI และแสดงผลหลังจาก build เสร็จสิ้น
         * 
         * @calledBy startBuildProcess() -> หลังจาก build เสร็จ
         * @calls addTerminalLine() -> แสดงผลลัพธ์
         * 
         * @sideEffects
         * - ลบ build animation
         * - แสดงข้อความผลลัพธ์
         * - อัพเดต UI elements
         */
        function onBuildComplete(success) {
            const buildStatusDiv = document.getElementById('build-status');
            if (buildStatusDiv) {
                if (success) {
                    buildStatusDiv.style.background = 'linear-gradient(135deg, #28a745, #1e7e34)';
                    buildStatusDiv.innerHTML = `
                        <div style="display: flex; align-items: center; justify-content: center;">
                            <span style="font-size: 1.2em; margin-right: 10px;"></span>
                            <span> Build เสร็จสมบูรณ์! ตรวจสอบไฟล์ในโฟลเดอร์ dist/</span>
                        </div>
                    `;
                    showNotification(' Build สำเร็จ! ไฟล์ MSI/EXE พร้อมใช้งาน', 'success');
                } else {
                    buildStatusDiv.style.background = 'linear-gradient(135deg, #dc3545, #c82333)';
                    buildStatusDiv.innerHTML = `
                        <div style="display: flex; align-items: center; justify-content: center;">
                            <span style="font-size: 1.2em; margin-right: 10px;"></span>
                            <span> Build ล้มเหลว! ตรวจสอบ Log เพื่อดูรายละเอียด</span>
                        </div>
                    `;
                    showNotification(' Build ล้มเหลว!', 'error');
                }
                
                // ลบ build status หลังจาก 10 วินาที
                setTimeout(() => {
                    buildStatusDiv.remove();
                }, 10000);
            }
        }
        
        //  ฟังก์ชัน createPluginButtons เวอร์ชันใหม่ที่ง่ายกว่าเดิม
        /**
         * ฟังก์ชันสร้างปุ่มสำหรับปลั๊กอิน
         * 
         * @function createPluginButtons
         * @param {Object} pluginData - ข้อมูลปลั๊กอิน
         * @param {string} pluginData.name - ชื่อปลั๊กอิน
         * @param {string} pluginData.type - ประเภทปลั๊กอิน (html, node, python, java)
         * @param {string} pluginData.path - path ของปลั๊กอิน
         * @param {Object} pluginData.manifest - ข้อมูล manifest
         * 
         * @description สร้าง HTML buttons สำหรับจัดการปลั๊กอินแต่ละตัว
         * 
         * @returns {string} HTML string ของปุ่มทั้งหมด
         * 
         * @dependencies
         * - startBuildProcess() -> สำหรับปุ่ม Build
         * - window.electronAPI -> APIs ต่างๆ
         * 
         * @calledBy
         * - scanAndRenderPlugins() -> สร้างปุ่มสำหรับปลั๊กอินแต่ละตัว
         * - scanAndRenderPluginsWithDebug() -> ใน debug mode
         * 
         * @sideEffects
         * - สร้าง HTML elements ใหม่
         * - เชื่อมโยง onclick events
         */
        function createPluginButtons(pluginData) {
            let buttonsHTML = '';
            if (pluginData.buttons && pluginData.buttons.length > 0) {
                pluginData.buttons.forEach(buttonInfo => {
                    // ไม่ต้องเปลี่ยน command เพราะเราแก้ไข button-generator.js แล้ว
                    buttonsHTML += `
                        <button 
                            onclick="runPluginAction('${pluginData.name}', '${buttonInfo.command}', '${pluginData.path.replace(/\\/g, '\\\\')}')"
                            title="${buttonInfo.tooltip || buttonInfo.name}"
                        >
                            ${buttonInfo.icon || ''} ${buttonInfo.name}
                        </button>
                    `;
                });
            }
            buttonsHTML += `<button onclick="runPluginAction('${pluginData.name}', 'info', '${pluginData.path.replace(/\\/g, '\\\\')}')" title="แสดงข้อมูล">ℹ ข้อมูล</button>`;
            return buttonsHTML || '<span>ไม่มีคำสั่งที่ใช้ได้</span>';
        }
        
        //  อัปเดตฟังก์ชัน getIconForType เล็กน้อย
        function getIconForType(pluginData) {
            // ใช้ icon จาก manifest เป็นหลัก ถ้าไม่มีก็ใช้แบบเดิม
            if (pluginData.icon) {
                return pluginData.icon;
            }
            
            // Fallback icons ตาม type
            const icons = { 
                'node': '', 
                'python': '', 
                'java': '', 
                'api': '',
                'html': '',
                'project': '', 
                'batch_project': '',
                'executable_project': '',
                'electron_app': '',
                'utility_tool': '',
                'chahuadev_studio': '', 
                'html_plugin': '', 
                'javascript_plugin': '' 
            };
            return icons[pluginData.type] || '';
        }

        // --- EVENT HANDLERS ---

        //  ฟังก์ชันสำหรับรันคำสั่งปลั๊กอิน - ส่ง action ไปให้ validation_gateway.js 
        /**
         * ฟังก์ชันรันคำสั่งเฉพาะของปลั๊กอิน
         * 
         * @function runPluginAction
         * @async
         * @param {string} pluginName - ชื่อปลั๊กอิน
         * @param {string} action - คำสั่งที่ต้องการรัน (run, build, test, install)
         * @param {string} projectPath - path ของโปรเจกต์ปลั๊กอิน
         * @description รันคำสั่งเฉพาะสำหรับปลั๊กอินแต่ละประเภท
         * 
         * @returns {Promise<void>}
         * 
         * @dependencies
         * - window.electronAPI.executePluginCommand() -> API รันคำสั่งปลั๊กอิน
         * 
         * @calledBy
         * - createPluginButtons() -> ปุ่มต่างๆ ของปลั๊กอิน
         * - onclick events ในปุ่ม Run, Build, Test
         * 
         * @calls addTerminalLine() -> แสดงผลการทำงาน
         * 
         * @throws {Error} เมื่อรันคำสั่งไม่สำเร็จ
         * 
         * @sideEffects
         * - รันคำสั่งใน plugin directory
         * - แสดงผลใน Log Viewer
         */
        async function runPluginAction(pluginName, action, projectPath) {
            addTerminalLine(` กำลังรัน Action: "${action}" บนปลั๊กอิน "${pluginName}"...`, 'command');
            
            try {
                // เรียกใช้ Gateway โดยตรงผ่านสะพานใหม่ที่เราสร้าง
                const result = await window.electronAPI.processCommand({
                    action: action, // ส่ง action name ที่ถูกต้องไปให้ validation_gateway.js
                    pluginName: pluginName,
                    projectPath: projectPath
                });
                
                if (result.success) {
                    addTerminalLine(` Action สำเร็จ!`, 'success');
                    const output = result.data?.output || result.data?.message || result.message;
                    if (output) {
                        addTerminalLine(output, 'stdout');
                    }
                } else {
                    addTerminalLine(` Action ล้มเหลว: ${result.error}`, 'error');
                }
            } catch (err) {
                addTerminalLine(` ข้อผิดพลาดร้ายแรง (IPC): ${err.message}`, 'error');
            }
        }
        // ทำให้ onclick เรียกใช้ได้
        window.runPluginAction = runPluginAction;

        // ฟังก์ชันใหม่สำหรับรันคำสั่งภายนอกผ่าน Main Process
        /**
         * ฟังก์ชันรันคำสั่งภายนอก (External Commands)
         * 
         * @function runExternalCommand
         * @async
         * @param {string} command - คำสั่งที่ต้องการรัน
         * @description รันคำสั่งภายนอกผ่าน Terminal API พร้อมการตรวจสอบความปลอดภัย
         * 
         * @returns {Promise<Object>} ผลลัพธ์การรันคำสั่ง
         * 
         * @dependencies
         * - window.electronAPI.terminal.executeCommand() -> Terminal API
         * - safeExternalCommands Set -> รายการคำสั่งที่ปลอดภัย
         * 
         * @calledBy
         * - Plugin action buttons
         * - Developer tools
         * 
         * @calls addTerminalLine() -> แสดงผลการทำงาน
         * 
         * @security
         * - ตรวจสอบคำสั่งที่อนุญาต (whitelist)
         * - ป้องกันการรัน malicious commands
         * 
         * @throws {Error} เมื่อคำสั่งไม่ปลอดภัยหรือรันไม่สำเร็จ
         */
        async function runExternalCommand(command) {
            try {
                // เรียกใช้ API ที่เราสร้างไว้ใน preload.js
                // main.js จะรับคำสั่งนี้ไปรันใน shell ของเครื่อง
                const result = await window.electronAPI.executeQuickCommand(command);

                if (result.success) {
                    // ถ้าสำเร็จ ให้นำผลลัพธ์ (output) มาแสดง
                    addTerminalLine(result.data.output, 'stdout');
                } else {
                    // ถ้าล้มเหลว ให้แสดงข้อผิดพลาด
                    addTerminalLine(result.error, 'error');
                }
            } catch (err) {
                // กรณีที่การเชื่อมต่อกับ Main Process มีปัญหา
                addTerminalLine(` IPC Error: ${err.message}`, 'error');
            }
        }
        
        //  ฟังก์ชันใหม่สำหรับรันคำสั่งผ่าน ValidationGateway
        /**
         * ฟังก์ชันรันคำสั่งผ่าน Gateway System
         * 
         * @function runGatewayCommand
         * @async
         * @param {string} action - คำสั่งที่ต้องการรัน
         * @param {string} [loadingMessage='กำลังดำเนินการ...'] - ข้อความแสดงขณะรัน
         * @description รันคำสั่งผ่าน validation_gateway.js เพื่อความปลอดภัย
         * 
         * @returns {Promise<Object>} ผลลัพธ์จาก gateway
         * 
         * @dependencies
         * - window.electronAPI.processCommand() -> Gateway API
         * - validation_gateway.js -> ระบบตรวจสอบคำสั่ง
         * 
         * @calledBy
         * - checkLicenseCommand() -> ตรวจสอบ license
         * - Plugin management functions
         * 
         * @calls addTerminalLine() -> แสดงสถานะการทำงาน
         * 
         * @security
         * - ผ่าน validation_gateway.js
         * - ตรวจสอบสิทธิ์การเข้าถึง
         * 
         * @sideEffects
         * - แสดงข้อความ loading
         * - รันคำสั่งใน system
         */
        async function runGatewayCommand(action, loadingMessage = 'กำลังดำเนินการ...') {
            try {
                addTerminalLine(loadingMessage, 'command');
                
                const result = await window.electronAPI.processCommand({
                    action: action,
                    projectPath: process.cwd ? process.cwd() : '.'
                });
                
                if (result.success) {
                    addTerminalLine(' คำสั่งสำเร็จ!', 'success');
                    if (result.data && result.data.output) {
                        addTerminalLine(result.data.output, 'stdout');
                    } else if (result.data && result.data.message) {
                        addTerminalLine(result.data.message, 'info');
                    }
                } else {
                    addTerminalLine(` คำสั่งล้มเหลว: ${result.error}`, 'error');
                }
            } catch (error) {
                addTerminalLine(` ข้อผิดพลาด: ${error.message}`, 'error');
            }
        }

        //  ลบฟังก์ชันการรันคำสั่ง เพราะเปลี่ยนเป็น log viewer แล้ว

        //  ฟังก์ชันเอฟเฟกต์พิเศษและอนิเมชั่น
        /**
         * ฟังก์ชันเพิ่มเอฟเฟกต์ความสำเร็จให้ Element
         * 
         * @function addSuccessEffect
         * @param {HTMLElement} element - Element ที่ต้องการเพิ่มเอฟเฟกต์
         * @description เพิ่ม CSS animation class สำหรับแสดงเอฟเฟกต์ความสำเร็จ
         * 
         * @dependencies
         * - CSS class 'success-animation' -> ต้องมี keyframe animation ใน CSS
         * 
         * @calledBy
         * - UI success callbacks -> เมื่อการดำเนินการสำเร็จ
         * - Plugin action completions -> หลังจากปลั๊กอินทำงานสำเร็จ
         * 
         * @sideEffects
         * - เพิ่ม/ลบ CSS class จาก element
         * - แสดง animation เป็นเวลา 600ms
         * 
         * @example
         * const button = document.getElementById('my-button');
         * addSuccessEffect(button); // แสดงเอฟเฟกต์ความสำเร็จ 600ms
         */
        function addSuccessEffect(element) {
            element.classList.add('success-animation');
            setTimeout(() => {
                element.classList.remove('success-animation');
            }, 600);
        }
        
        /**
         * ฟังก์ชันเพิ่มเอฟเฟกต์ Ripple เมื่อคลิก
         * 
         * @function addClickEffect
         * @param {Event} event - Mouse click event object
         * @description สร้างเอฟเฟกต์ ripple animation เมื่อคลิกปุ่ม
         * 
         * @dependencies
         * - CSS keyframe 'ripple' -> สร้างอัตโนมัติถ้าไม่มี
         * - DOM manipulation -> สร้าง span element สำหรับ ripple
         * 
         * @calledBy
         * - initializeButtonEffects() -> document click listener
         * - Button click events -> ทุกปุ่มในแอป
         * 
         * @calls
         * - createElement() -> สร้าง ripple element
         * - getBoundingClientRect() -> คำนวณตำแหน่ง
         * 
         * @sideEffects
         * - เพิ่ม CSS style ใน document head (ครั้งแรกเท่านั้น)
         * - สร้างและลบ DOM elements ชั่วคราว
         * - เปลี่ยน style ของปุ่มเป็น relative position
         * 
         * @example
         * // จะถูกเรียกอัตโนมัติเมื่อคลิกปุ่มใดๆ
         * button.addEventListener('click', addClickEffect);
         */
        function addClickEffect(event) {
            const button = event.target;
            
            // สร้าง ripple effect
            const ripple = document.createElement('span');
            const rect = button.getBoundingClientRect();
            const size = Math.max(rect.width, rect.height);
            const x = event.clientX - rect.left - size / 2;
            const y = event.clientY - rect.top - size / 2;
            
            ripple.style.cssText = `
                position: absolute;
                width: ${size}px;
                height: ${size}px;
                left: ${x}px;
                top: ${y}px;
                background: rgba(255, 255, 255, 0.6);
                border-radius: 50%;
                transform: scale(0);
                animation: ripple 0.6s linear;
                pointer-events: none;
            `;
            
            // เพิ่ม keyframe สำหรับ ripple animation
            if (!document.querySelector('#ripple-style')) {
                const style = document.createElement('style');
                style.id = 'ripple-style';
                style.textContent = `
                    @keyframes ripple {
                        to {
                            transform: scale(4);
                            opacity: 0;
                        }
                    }
                `;
                document.head.appendChild(style);
            }
            
            button.style.position = 'relative';
            button.style.overflow = 'hidden';
            button.appendChild(ripple);
            
            setTimeout(() => {
                ripple.remove();
            }, 600);
        }
        
        /**
         * ฟังก์ชันเพิ่มเอฟเฟกต์การพิมพ์ทีละตัวอักษร
         * 
         * @function addTypingEffect
         * @param {HTMLElement} element - Element ที่จะแสดงข้อความ
         * @param {string} text - ข้อความที่ต้องการแสดงแบบพิมพ์
         * @param {number} [speed=50] - ความเร็วในการพิมพ์ (milliseconds ต่อตัวอักษร)
         * @description สร้างเอฟเฟกต์การพิมพ์ข้อความทีละตัวอักษรแบบ typewriter
         * 
         * @dependencies
         * - CSS class 'typing-effect' -> สำหรับ styling ขณะพิมพ์
         * 
         * @calledBy
         * - Welcome messages -> ข้อความต้อนรับ
         * - Status updates -> อัพเดตสถานะที่สำคัญ
         * 
         * @calls
         * - setTimeout() -> ควบคุมความเร็วการพิมพ์
         * - charAt() -> ดึงตัวอักษรทีละตัว
         * 
         * @sideEffects
         * - เปลี่ยน textContent ของ element
         * - เพิ่ม/ลบ CSS class 'typing-effect'
         * - ใช้ recursive setTimeout
         * 
         * @example
         * const messageEl = document.getElementById('message');
         * addTypingEffect(messageEl, 'สวัสดี!', 100); // พิมพ์ช้าๆ
         */
        function addTypingEffect(element, text, speed = 50) {
            element.textContent = '';
            element.classList.add('typing-effect');
            
            let i = 0;
            const typeWriter = () => {
                if (i < text.length) {
                    element.textContent += text.charAt(i);
                    i++;
                    setTimeout(typeWriter, speed);
                } else {
                    element.classList.remove('typing-effect');
                }
            };
            typeWriter();
        }
        
        // เพิ่ม event listener สำหรับปุ่มทั้งหมด
        /**
         * ฟังก์ชันเริ่มต้นระบบเอฟเฟกต์ปุ่ม
         * 
         * @function initializeButtonEffects
         * @description ตั้งค่า global event listener สำหรับเอฟเฟกต์ปุ่มทั้งหมด
         * 
         * @dependencies
         * - addClickEffect() -> เอฟเฟกต์ ripple
         * 
         * @calledBy
         * - DOMContentLoaded event -> เริ่มต้นระบบ
         * 
         * @calls
         * - addEventListener() -> ตั้งค่า global click listener
         * - addClickEffect() -> เมื่อคลิกปุ่ม
         * 
         * @sideEffects
         * - เพิ่ม global click event listener
         * - ทุกปุ่มจะมีเอฟเฟกต์ ripple อัตโนมัติ
         * 
         * @example
         * // เรียกครั้งเดียวตอน init
         * initializeButtonEffects();
         */
        function initializeButtonEffects() {
            document.addEventListener('click', (event) => {
                if (event.target.tagName === 'BUTTON') {
                    addClickEffect(event);
                }
            });
        }
        
        //  ฟังก์ชันสำหรับเพิ่มอนิเมชั่นแบบ Stagger (เรียงลำดับ)
        /**
         * ฟังก์ชันเพิ่มอนิเมชั่นแบบ Stagger สำหรับ Plugin Cards
         * 
         * @function animatePluginCards
         * @description เพิ่มอนิเมชั่น fadeIn ให้ plugin cards โดยมีช่วงเวลาต่างกัน
         * 
         * @dependencies
         * - CSS class 'fadeIn' -> ต้องมี keyframe animation ใน CSS
         * - DOM selector '.plugin-card' -> plugin card elements
         * 
         * @calledBy
         * - scanAndRenderPlugins() -> หลังจากแสดงปลั๊กอินเสร็จ
         * - createPluginButtons() -> เมื่อสร้าง plugin UI
         * 
         * @calls
         * - querySelectorAll() -> หา plugin cards ทั้งหมด
         * - forEach() -> วนลูปเพิ่ม animation
         * 
         * @sideEffects
         * - เปลี่ยน animationDelay ของแต่ละ card
         * - เพิ่ม CSS class 'fadeIn'
         * 
         * @algorithm
         * 1. หา plugin cards ทั้งหมด
         * 2. เพิ่ม delay แต่ละ card (index * 0.1s)
         * 3. เพิ่ม fadeIn class สำหรับ animation
         */
        function animatePluginCards() {
            const cards = document.querySelectorAll('.plugin-card');
            cards.forEach((card, index) => {
                card.style.animationDelay = `${index * 0.1}s`;
                card.classList.add('fadeIn');
            });
        }
        
        //  ฟังก์ชันสำหรับ Loading Animation - with safety check
        /**
         * ฟังก์ชันแสดง Loading Animation
         * 
         * @function showLoadingAnimation
         * @param {HTMLElement} element - Element ที่จะแสดง loading animation
         * @param {string} [text='กำลังโหลด'] - ข้อความที่แสดงใต้ spinner
         * @description แสดง loading spinner พร้อมข้อความในใน element ที่กำหนด
         * 
         * @dependencies
         * - CSS keyframe 'spin' -> สร้างอัตโนมัติถ้าไม่มี
         * 
         * @calledBy
         * - scanAndRenderPlugins() -> ขณะสแกนปลั๊กอิน
         * - runGeneratorAndRefresh() -> ขณะสร้าง manifest
         * - Plugin loading operations -> การโหลดปลั๊กอิน
         * 
         * @calls
         * - console.warn() -> เตือนเมื่อ element เป็น null
         * - createElement() -> สร้าง style element สำหรับ keyframe
         * 
         * @sideEffects
         * - เปลี่ยน innerHTML ของ element
         * - เพิ่ม CSS keyframe 'spin' ใน document head
         * 
         * @safety
         * - ตรวจสอบ element null/undefined ก่อนใช้งาน
         * - ป้องกัน error จาก null reference
         * 
         * @example
         * showLoadingAnimation(pluginContainer, 'กำลังสแกนปลั๊กอิน');
         */
        function showLoadingAnimation(element, text = 'กำลังโหลด') {
            // Add safety check to prevent null element error
            if (!element) {
                console.warn(' showLoadingAnimation: Element is null or undefined');
                return;
            }
            
            element.innerHTML = `
                <div class="loading-container" style="text-align: center; padding: 20px;">
                    <div class="loading-spinner" style="
                        width: 40px;
                        height: 40px;
                        border: 4px solid #e9ecef;
                        border-top: 4px solid #667eea;
                        border-radius: 50%;
                        animation: spin 1s linear infinite;
                        margin: 0 auto 10px;
                    "></div>
                    <div class="loading-text">${text}</div>
                </div>
            `;
            
            // เพิ่ม keyframe สำหรับ spinner
            if (!document.querySelector('#spinner-style')) {
                const style = document.createElement('style');
                style.id = 'spinner-style';
                style.textContent = `
                    @keyframes spin {
                        0% { transform: rotate(0deg); }
                        100% { transform: rotate(360deg); }
                    }
                `;
                document.head.appendChild(style);
            }
        }
        
        
        //  ฟังก์ชันทดแทนเพื่อป้องกันข้อผิดพลาด - ไม่แสดง notification
        /**
         * ฟังก์ชันแสดง Notification (ปิดใช้งาน)
         * 
         * @function showNotification
         * @param {string} message - ข้อความที่ต้องการแสดง
         * @param {string} [type='info'] - ประเภทของ notification (info, success, error, warning)
         * @description ฟังก์ชันทดแทนสำหรับระบบ notification (ปิดใช้งานเพื่อไม่รบกวนระบบ)
         * 
         * @deprecated ปิดใช้งานเพื่อไม่ให้บังระบบการทำงานหลัก
         * 
         * @calledBy
         * - สถานที่ที่เคยใช้ notification system
         * - ฟังก์ชันต่างๆ ที่ต้องการแจ้งเตือน
         * 
         * @calls console.log() -> แสดงข้อความใน console แทน
         * 
         * @sideEffects
         * - ไม่มี UI notification
         * - แสดงเฉพาะใน console log
         * 
         * @note
         * - หากต้องการเปิดใช้งานอีกครั้ง ให้ uncomment โค้ดการแสดง notification
         * - ออกแบบเพื่อป้องกัน error จากการเรียกฟังก์ชันที่ไม่มี
         */
        function showNotification(message, type = 'info') {
            //  ปิดการใช้งาน notification เพื่อไม่ให้บังระบบการทำงาน
            // หากต้องการเปิดใช้งานอีกครั้ง ให้ uncomment บรรทัดด้านบน
            console.log(` [Notification Disabled] ${message} (${type})`);
        }
        
        // --- INITIALIZATION ---
        
        // =============================================================
        //  PRODUCTION SECURITY SYSTEM (Same as debugger.html)
        // =============================================================
        
        // Development Mode Detection
        /**
         * ฟังก์ชันตรวจสอบโหมด Development
         * 
         * @function isDevMode
         * @returns {boolean} true ถ้าอยู่ในโหมด development, false ถ้าเป็น production
         * @description ตรวจสอบจากหลายแหล่งว่าแอปกำลังทำงานในโหมด development หรือไม่
         * 
         * @dependencies
         * - URLSearchParams -> ตรวจสอบ ?dev=true
         * - localStorage -> ตรวจสอบ 'chahua_dev_mode'
         * - window.location -> ตรวจสอบ hostname
         * 
         * @calledBy
         * - initProductionSecurity() -> เช็คโหมดก่อนปิด security
         * - DOMContentLoaded event -> ตั้งค่าเริ่มต้น
         * - devLog(), devError(), devWarn() -> ควบคุมการแสดง log
         * 
         * @algorithm
         * 1. เช็ค URL parameter ?dev=true
         * 2. เช็ค localStorage chahua_dev_mode = 'true'
         * 3. เช็ค hostname เป็น localhost/127.0.0.1
         * 4. return true ถ้าเงื่อนไขใดเงื่อนไขหนึ่งเป็น true
         * 
         * @security
         * - ป้องกันการเปิด dev mode ใน production โดยไม่ตั้งใจ
         * - ใช้หลายเงื่อนไขเพื่อความแม่นยำ
         */
        function isDevMode() {
            // Check multiple indicators for dev mode
            const urlParams = new URLSearchParams(window.location.search);
            const devParam = urlParams.get('dev') === 'true';
            const devStorage = localStorage.getItem('chahua_dev_mode') === 'true';
            const isLocalhost = window.location.hostname === 'localhost' || 
                               window.location.hostname === '127.0.0.1' ||
                               window.location.hostname === '';
            
            return devParam || devStorage || isLocalhost;
        }

        // Production Security Implementation
        /**
         * ฟังก์ชันเริ่มต้นระบบรักษาความปลอดภัยแบบ Production
         * 
         * @function initProductionSecurity
         * @returns {boolean} true ถ้าเป็น dev mode, false ถ้าเป็น production mode
         * @description เริ่มต้นระบบรักษาความปลอดภัยเมื่อไม่ใช่ development mode
         * 
         * @dependencies
         * - isDevMode() -> ตรวจสอบโหมดการทำงาน
         * - showDeveloperToolsWarning() -> แสดงคำเตือนเมื่อเปิด dev tools
         * 
         * @calledBy
         * - DOMContentLoaded event -> เริ่มต้นระบบความปลอดภัย
         * 
         * @calls
         * - isDevMode() -> ตรวจสอบโหมด
         * - addEventListener() -> บล็อค shortcuts และ context menu
         * - setInterval() -> ตรวจสอบ developer tools
         * 
         * @sideEffects
         * - ปิด console methods ใน production mode
         * - บล็อค keyboard shortcuts (F12, Ctrl+Shift+I, etc.)
         * - ปิด right-click context menu
         * - ปิดการเลือกข้อความและ drag
         * - ตรวจสอบ developer tools แบบ real-time
         * 
         * @security Features:
         * 1. Console Methods Disabling -> ป้องกันการ debug ใน console
         * 2. Keyboard Shortcuts Blocking -> บล็อค F12, Ctrl+Shift+I/J/C, Ctrl+U/S
         * 3. Context Menu Disabling -> ปิด right-click menu
         * 4. Text Selection Blocking -> ป้องกันการคัดลอกโค้ด
         * 5. Developer Tools Detection -> เตือนเมื่อเปิด dev tools
         * 
         * @example
         * // เรียกตอน app initialization
         * const isDev = initProductionSecurity();
         */
        function initProductionSecurity() {
            const isDev = isDevMode();
            console.log(' Security Mode:', isDev ? 'DEVELOPMENT' : 'PRODUCTION');
            
            if (!isDev) {
                // 1. Disable Console Methods
                const consoleMethods = ['log', 'debug', 'info', 'warn', 'error', 'assert', 'dir', 'dirxml', 
                                      'group', 'groupEnd', 'time', 'timeEnd', 'count', 'trace', 'profile', 'profileEnd'];
                
                consoleMethods.forEach(method => {
                    console[method] = function() {
                        // Silent in production
                    };
                });
                
                // 2. Block Developer Shortcuts
                document.addEventListener('keydown', function(e) {
                    // Block F12
                    if (e.key === 'F12') {
                        e.preventDefault();
                        e.stopPropagation();
                        return false;
                    }
                    
                    // Block Ctrl+Shift+I (Developer Tools)
                    if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'I') {
                        e.preventDefault();
                        e.stopPropagation();
                        return false;
                    }
                    
                    // Block Ctrl+Shift+J (Console)
                    if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'J') {
                        e.preventDefault();
                        e.stopPropagation();
                        return false;
                    }
                    
                    // Block Ctrl+Shift+C (Element Inspector)
                    if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'C') {
                        e.preventDefault();
                        e.stopPropagation();
                        return false;
                    }
                    
                    // Block Ctrl+U (View Source)
                    if ((e.ctrlKey || e.metaKey) && e.key === 'u') {
                        e.preventDefault();
                        e.stopPropagation();
                        return false;
                    }
                    
                    // Block Ctrl+S (Save)
                    if ((e.ctrlKey || e.metaKey) && e.key === 's') {
                        e.preventDefault();
                        e.stopPropagation();
                        return false;
                    }
                }, true);
                
                // 3. Disable Right-Click Context Menu
                document.addEventListener('contextmenu', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    return false;
                }, true);
                
                // 4. Disable Text Selection and Drag
                document.addEventListener('selectstart', function(e) {
                    e.preventDefault();
                    return false;
                }, true);
                
                document.addEventListener('dragstart', function(e) {
                    e.preventDefault();
                    return false;
                }, true);
                
                // 5. Developer Tools Detection
                let devtools = {
                    open: false,
                    orientation: null
                };
                
                const threshold = 160;
                
                setInterval(() => {
                    if (window.outerHeight - window.innerHeight > threshold || 
                        window.outerWidth - window.innerWidth > threshold) {
                        if (!devtools.open) {
                            devtools.open = true;
                            showDeveloperToolsWarning();
                        }
                    } else {
                        devtools.open = false;
                        hideDeveloperToolsWarning();
                    }
                }, 500);
                
                // Additional detection methods
                let startTime = new Date();
                debugger;
                let endTime = new Date();
                if (endTime - startTime > 100) {
                    showDeveloperToolsWarning();
                }
            }
            
            return isDev;
        }

        // Developer Tools Warning System
        /**
         * ฟังก์ชันแสดงคำเตือนเมื่อเปิด Developer Tools
         * 
         * @function showDeveloperToolsWarning
         * @description แสดง overlay เตือนผู้ใช้เมื่อตรวจพบการเปิด Developer Tools ใน Production Mode
         * 
         * @dependencies
         * - DOM manipulation -> สร้าง warning overlay
         * 
         * @calledBy
         * - initProductionSecurity() -> เมื่อตรวจพบ dev tools
         * - Developer tools detection algorithms
         * 
         * @calls
         * - getElementById() -> ตรวจสอบว่าแสดงอยู่แล้วหรือไม่
         * - createElement() -> สร้าง warning element
         * 
         * @sideEffects
         * - สร้าง fullscreen overlay
         * - บล็อค interaction กับแอป
         * - แสดงข้อความเตือนความปลอดภัย
         * 
         * @security
         * - ป้องกันการใช้ dev tools ใน production
         * - แจ้งให้ผู้ใช้ปิด dev tools
         * - แนะนำ ?dev=true สำหรับนักพัฒนา
         * 
         * @ui Components:
         * - Full-screen red overlay
         * - Warning icon และข้อความ
         * - คำแนะนำสำหรับนักพัฒนา
         * - Backdrop blur effect
         */
        function showDeveloperToolsWarning() {
            if (document.getElementById('dev-tools-warning')) return;
            
            const warningOverlay = document.createElement('div');
            warningOverlay.id = 'dev-tools-warning';
            warningOverlay.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(220, 53, 69, 0.95);
                color: white;
                z-index: 999999;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                font-family: 'Segoe UI', sans-serif;
                font-size: 24px;
                text-align: center;
                backdrop-filter: blur(10px);
            `;
            
            warningOverlay.innerHTML = `
                <div style="max-width: 600px; padding: 40px; background: rgba(0,0,0,0.8); border-radius: 20px; border: 3px solid #dc3545;">
                    <h1 style="color: #ff6b6b; margin-bottom: 20px; font-size: 2.5em;"> การเข้าถึงถูกปฏิเสธ</h1>
                    <p style="font-size: 1.2em; margin-bottom: 20px; line-height: 1.6;">
                        ระบบตรวจพบการเปิด Developer Tools<br/>
                        แอปพลิเคชันนี้ได้รับการป้องกันเพื่อความปลอดภัย
                    </p>
                    <div style="background: rgba(255,255,255,0.1); padding: 20px; border-radius: 10px; margin: 20px 0;">
                        <p style="font-size: 1em; margin: 0;">
                             Production Mode Active<br/>
                             Security Features Enabled<br/>
                             For End Users Only
                        </p>
                    </div>
                    <p style="font-size: 0.9em; color: #ffcccb;">
                        กรุณาปิด Developer Tools เพื่อใช้งานต่อ<br/>
                        หากคุณเป็นนักพัฒนา ให้เพิ่ม ?dev=true ใน URL
                    </p>
                </div>
            `;
            
            document.body.appendChild(warningOverlay);
        }

        /**
         * ฟังก์ชันซ่อนคำเตือน Developer Tools
         * 
         * @function hideDeveloperToolsWarning
         * @description ลบ warning overlay เมื่อผู้ใช้ปิด Developer Tools
         * 
         * @calledBy
         * - initProductionSecurity() -> เมื่อ dev tools ถูกปิด
         * - Developer tools detection -> เมื่อไม่พบ dev tools
         * 
         * @calls
         * - getElementById() -> หา warning element
         * - remove() -> ลบ element
         * 
         * @sideEffects
         * - ลบ warning overlay
         * - ปล่อยให้ผู้ใช้ใช้งานแอปได้ต่อ
         * 
         * @safety
         * - ตรวจสอบว่า element มีอยู่ก่อนลบ
         * - ป้องกัน error จาก null reference
         */
        function hideDeveloperToolsWarning() {
            const warning = document.getElementById('dev-tools-warning');
            if (warning) {
                warning.remove();
            }
        }

        // Enhanced Console Logging (Only in Dev Mode)
        /**
         * ฟังก์ชัน Console Log สำหรับ Developer Mode เท่านั้น
         * 
         * @function devLog
         * @param {...any} args - arguments ที่จะส่งไป console.log
         * @description แสดง console.log เฉพาะใน development mode
         * 
         * @dependencies
         * - isDevMode() -> ตรวจสอบโหมดก่อนแสดง log
         * 
         * @calledBy
         * - ทุกที่ที่ต้องการ debug log แต่ไม่ต้องการแสดงใน production
         * 
         * @calls
         * - isDevMode() -> เช็คโหมด
         * - console.log() -> แสดงข้อความ (dev mode เท่านั้น)
         * 
         * @sideEffects
         * - แสดงข้อความใน browser console (dev mode เท่านั้น)
         * 
         * @security
         * - ไม่แสดงข้อมูล sensitive ใน production
         * 
         * @example
         * devLog('Debug information:', data); // แสดงเฉพาะใน dev mode
         */
        function devLog(...args) {
            if (isDevMode()) {
                console.log(...args);
            }
        }

        /**
         * ฟังก์ชัน Console Error สำหรับ Developer Mode เท่านั้น
         * 
         * @function devError
         * @param {...any} args - arguments ที่จะส่งไป console.error
         * @description แสดง console.error เฉพาะใน development mode
         * 
         * @dependencies
         * - isDevMode() -> ตรวจสอบโหมดก่อนแสดง error
         * 
         * @calledBy
         * - Error handling ในโหมดพัฒนา
         * - Debug error messages
         * 
         * @calls
         * - isDevMode() -> เช็คโหมด
         * - console.error() -> แสดงข้อผิดพลาด (dev mode เท่านั้น)
         * 
         * @sideEffects
         * - แสดงข้อผิดพลาดใน browser console (dev mode เท่านั้น)
         * 
         * @security
         * - ไม่เปิดเผยข้อมูล error ใน production
         * 
         * @example
         * devError('API Error:', error.message); // แสดงเฉพาะใน dev mode
         */
        function devError(...args) {
            if (isDevMode()) {
                console.error(...args);
            }
        }

        /**
         * ฟังก์ชัน Console Warning สำหรับ Developer Mode เท่านั้น
         * 
         * @function devWarn
         * @param {...any} args - arguments ที่จะส่งไป console.warn
         * @description แสดง console.warn เฉพาะใน development mode
         * 
         * @dependencies
         * - isDevMode() -> ตรวจสอบโหมดก่อนแสดง warning
         * 
         * @calledBy
         * - Warning messages ในโหมดพัฒนา
         * - Deprecation warnings
         * 
         * @calls
         * - isDevMode() -> เช็คโหมด
         * - console.warn() -> แสดงคำเตือน (dev mode เท่านั้น)
         * 
         * @sideEffects
         * - แสดงคำเตือนใน browser console (dev mode เท่านั้น)
         * 
         * @security
         * - ไม่เปิดเผยข้อมูล warning ใน production
         * 
         * @example
         * devWarn('Deprecated function used:', functionName); // แสดงเฉพาะใน dev mode
         */
        function devWarn(...args) {
            if (isDevMode()) {
                console.warn(...args);
            }
        }

        // =============================================================
        //  END SECURITY SYSTEM
        // =============================================================

        document.addEventListener('DOMContentLoaded', async () => {
            // Initialize Security System First
            const isDev = initProductionSecurity();
            
            // ประกาศตัวแปร isDev ใน scope ที่เข้าถึงได้
            window.isDev = isDev; 
            
            addTerminalLine('กำลังเริ่มต้นระบบ...', 'info');
            
            if (isDev) {
                addTerminalLine(' Developer Mode: Security features disabled for development', 'warning');
                document.body.classList.add('dev-mode');
            } else {
                addTerminalLine(' Production Mode: Security features active', 'success');
                document.body.classList.remove('dev-mode');
            }
            
            if (window.electronAPI) {
                addTerminalLine('สคริปต์โหลดเสร็จสิ้น เชื่อมต่อกับระบบหลักแล้ว', 'success');
                
                // ตรวจสอบโหมดการทำงาน (นักพัฒนา vs ลูกค้า)
                try {
                    const runMode = await window.electronAPI.getRunMode();
                    if (runMode.isDevMode) {
                        console.log('ทำงานในโหมดนักพัฒนา - แสดงฟีเจอร์สำหรับนักพัฒนา');
                        addTerminalLine('โหมดนักพัฒนา: เปิดใช้งานฟีเจอร์สำหรับนักพัฒนา', 'success');
                        window.isDev = true; // ตั้งค่า isDev เป็น true
                        document.body.classList.add('dev-mode');
                        
                        showNotification('โหมดนักพัฒนา: เครื่องมือพิเศษพร้อมใช้งาน', 'info');
                    } else {
                        console.log('ทำงานในโหมดลูกค้า - ซ่อนฟีเจอร์สำหรับนักพัฒนา');
                        addTerminalLine('โหมดลูกค้า: เฉพาะฟีเจอร์สำหรับผู้ใช้ทั่วไป', 'info');
                        document.body.classList.remove('dev-mode');
                        
                        showNotification('เวอร์ชันลูกค้า - พร้อมใช้งาน!', 'success');
                    }
                } catch (error) {
                    console.error('ไม่สามารถตรวจสอบโหมดการทำงานได้:', error);
                    addTerminalLine('ไม่สามารถตรวจสอบโหมดการทำงาน - ใช้โหมดปกติ', 'warning');
                    // Default: ถ้าเช็คไม่ได้ให้ใช้โหมดลูกค้า (ปลอดภัยกว่า)
                    document.body.classList.remove('dev-mode');
                }
                
                // เริ่มต้น effects
                initializeButtonEffects();
                
                //  ลบ command input event listeners เพราะเปลี่ยนเป็น log viewer แล้ว
                
                
                // เพิ่มข้อความต้อนรับใน Log Viewer
                addTerminalLine('===== Chahua Plugin Management System =====', 'success');
                addTerminalLine('ระบบจัดการปลั๊กอิน - โหมด Log Viewer', 'info');
                addTerminalLine('ข้อความจากระบบและปุ่มต่างๆ จะแสดงที่นี่', 'info');
                addTerminalLine('', 'info');

                setTimeout(() => {
                    scanAndRenderPlugins();
                }, 1000);
                
                //  เพิ่ม: เฝ้าฟัง Log จากกระบวนการ Build แบบ Real-time
                window.electronAPI.onBuildLog((log) => {
                    // ตรวจสอบว่าเป็น Error Log หรือไม่
                    if (log.includes('[ERROR]')) {
                        addTerminalLine(log.replace('[ERROR] ', ''), 'error');
                    } else if (log.includes('') || log.includes('')) {
                        addTerminalLine(log, 'success');
                        // เรียกฟังก์ชันเมื่อ Build สำเร็จ
                        if (log.includes('Build เสร็จสมบูรณ์')) {
                            onBuildComplete(true);
                        }
                    } else if (log.includes('') || log.includes('')) {
                        addTerminalLine(log, 'error');
                        // เรียกฟังก์ชันเมื่อ Build ล้มเหลว
                        if (log.includes('Build ล้มเหลว')) {
                            onBuildComplete(false);
                        }
                    } else {
                        // Log ปกติ
                        addTerminalLine(log, 'stdout');
                    }
                });
                
                //  เพิ่ม: เฝ้าฟัง Enhanced Scan Complete จาก Menu
                if (window.electronAPI && window.electronAPI.onEnhancedScanComplete) {
                    window.electronAPI.onEnhancedScanComplete((result) => {
                        console.log(' Enhanced scan complete from menu:', result);
                        if (result.success) {
                            addTerminalLine(' Enhanced scan completed via keyboard shortcut', 'success');
                            // อัปเดตการแสดงผลปลั๊กอิน
                            scanAndRenderPluginsWithDebug();
                        } else {
                            addTerminalLine(` Enhanced scan failed: ${result.error}`, 'error');
                        }
                    });
                }
                
                // แสดง welcome notification
                setTimeout(() => {
                    showNotification('ยินดีต้อนรับสู่ระบบจัดการปลั๊กอิน Chahuadev!', 'success');
                }, 2000);
                

                
                //  Initialize license dropdown
                initializeLicenseDropdown();
                
                //  Initialize resize panel system
                window.resizeController = new ResizePanelController();
                
                //  Parameterized Diagnostics System
                initParameterizedDiagnostics();
                
                //  System Check Button Event Listener
                const systemCheckBtn = document.getElementById('runSystemCheckBtn');
                if (systemCheckBtn) {
                    systemCheckBtn.addEventListener('click', async () => {
                        const scope = document.getElementById('diagnosticScope').value;
                        const selectedPlugins = scope === 'specific' ? getSelectedPlugins() : [];
                        
                        addTerminalLine(` กำลังเริ่มการวินิจฉัย (${getDiagnosticScopeText(scope)})...`, 'info');
                        
                        try {
                            const result = await window.electronAPI.runParameterizedSystemCheck({
                                scope: scope,
                                plugins: selectedPlugins
                            });
                            
                            if (result.success) {
                                addTerminalLine(' การวินิจฉัยเสร็จสิ้น', 'success');
                                if (result.message) {
                                    addTerminalLine(result.message, 'info');
                                }
                                if (result.fixed) {
                                    addTerminalLine(' ระบบได้รับการซ่อมแซมเรียบร้อยแล้ว', 'success');
                                }
                                if (result.recommendations && result.recommendations.length > 0) {
                                    addTerminalLine(` คำแนะนำ: ${result.recommendations.join(', ')}`, 'info');
                                }
                            } else {
                                addTerminalLine(` การวินิจฉัยล้มเหลว: ${result.error}`, 'error');
                            }
                        } catch (error) {
                            addTerminalLine(` ไม่สามารถเริ่มการวินิจฉัยได้: ${error.message}`, 'error');
                        }
                    });
                }
                
            } else {
                 addTerminalLine('ข้อผิดพลาดร้ายแรง: ไม่พบสคริปต์โหลด (electronAPI)!', 'error');
            }
        });
        


        //  Parameterized Diagnostics Functions
        /**
         * ฟังก์ชันเริ่มต้นระบบ Parameterized Diagnostics
         * 
         * @function initParameterizedDiagnostics
         * @description ตั้งค่า event listeners สำหรับระบบวินิจฉัยแบบกำหนดพารามิเตอร์ได้
         * 
         * @dependencies
         * - DOM elements: diagnosticScope, specificPluginSelector
         * 
         * @calledBy
         * - DOMContentLoaded event -> เริ่มต้นระบบ
         * 
         * @calls
         * - addEventListener() -> ตั้งค่า scope change listener
         * - loadAvailablePlugins() -> โหลดปลั๊กอินเมื่อเลือก specific
         * - updateDiagnosticButtonText() -> อัพเดตข้อความปุ่ม
         * 
         * @sideEffects
         * - เพิ่ม event listeners
         * - ควบคุมการแสดง/ซ่อน plugin selector
         * - อัพเดต UI text ตาม scope ที่เลือก
         * 
         * @features
         * - Scope Selection (all/project-only/specific)
         * - Dynamic Plugin List Loading
         * - Button Text Updates
         */
        function initParameterizedDiagnostics() {
            const diagnosticScope = document.getElementById('diagnosticScope');
            const specificPluginSelector = document.getElementById('specificPluginSelector');
            
            if (diagnosticScope) {
                diagnosticScope.addEventListener('change', function() {
                    if (this.value === 'specific') {
                        specificPluginSelector.style.display = 'block';
                        loadAvailablePlugins();
                    } else {
                        specificPluginSelector.style.display = 'none';
                    }
                    
                    // อัปเดตข้อความปุ่ม
                    updateDiagnosticButtonText(this.value);
                });
            }
        }
        
        /**
         * ฟังก์ชันโหลดปลั๊กอินที่มีให้ใช้งาน
         * 
         * @function loadAvailablePlugins
         * @async
         * @description โหลดรายการปลั๊กอินจาก Marketplace/Store
         * 
         * @returns {Promise<void>}
         * 
         * @dependencies
         * - window.electronAPI -> APIs สำหรับ marketplace
         * 
         * @calledBy
         * - Store/Marketplace view switching
         * - Refresh marketplace button
         * 
         * @calls addTerminalLine() -> แสดงสถานะการโหลด
         * 
         * @sideEffects
         * - อัพเดต Marketplace UI
         * - โหลดข้อมูลจาก remote server
         */
        async function loadAvailablePlugins() {
            const pluginList = document.getElementById('pluginList');
            if (!pluginList) return;
            
            try {
                // ดึงรายชื่อปลั๊กอินที่ตรวจพบ
                const result = await window.electronAPI.getAvailablePlugins();
                
                if (result.success) {
                    pluginList.innerHTML = '';
                    result.plugins.forEach(plugin => {
                        const option = document.createElement('option');
                        option.value = plugin.path;
                        option.textContent = `${plugin.name} (${plugin.type})`;
                        pluginList.appendChild(option);
                    });
                    
                    if (result.plugins.length === 0) {
                        const option = document.createElement('option');
                        option.textContent = 'ไม่พบปลั๊กอิน';
                        option.disabled = true;
                        pluginList.appendChild(option);
                    }
                } else {
                    pluginList.innerHTML = '<option disabled>ไม่สามารถโหลดรายชื่อปลั๊กอินได้</option>';
                }
            } catch (error) {
                console.error('Error loading plugins:', error);
                pluginList.innerHTML = '<option disabled>เกิดข้อผิดพลาดในการโหลด</option>';
            }
        }
        
        /**
         * ฟังก์ชันดึงปลั๊กอินที่ถูกเลือก
         * 
         * @function getSelectedPlugins
         * @returns {string[]} array ของ plugin paths ที่ถูกเลือก
         * @description ดึงปลั๊กอินที่ผู้ใช้เลือกจาก multi-select dropdown
         * 
         * @dependencies
         * - DOM element 'pluginList' -> dropdown element
         * 
         * @calledBy
         * - Diagnostic system -> เมื่อต้องการรายการปลั๊กอินที่เลือก
         * - System check functions -> สำหรับ specific scope
         * 
         * @returns
         * - empty array ถ้าไม่มี element หรือไม่มีการเลือก
         * - array of plugin paths ที่ถูกเลือก
         * 
         * @example
         * const selectedPlugins = getSelectedPlugins();
         * // ['path/to/plugin1', 'path/to/plugin2']
         */
        function getSelectedPlugins() {
            const pluginList = document.getElementById('pluginList');
            if (!pluginList) return [];
            
            const selected = [];
            for (let option of pluginList.selectedOptions) {
                selected.push(option.value);
            }
            return selected;
        }
        
        /**
         * ฟังก์ชันแปลง Diagnostic Scope เป็นข้อความไทย
         * 
         * @function getDiagnosticScopeText
         * @param {string} scope - diagnostic scope ('all', 'plugins', 'core', 'dependencies', 'specific')
         * @returns {string} ข้อความภาษาไทยสำหรับ scope ที่กำหนด
         * @description แปลง scope code เป็นข้อความแสดงผลภาษาไทย
         * 
         * @calledBy
         * - updateDiagnosticButtonText() -> อัพเดตข้อความปุ่ม
         * - Diagnostic UI functions -> แสดงข้อความใน log
         * 
         * @example
         * getDiagnosticScopeText('all'); // 'ทั้งระบบ'
         * getDiagnosticScopeText('plugins'); // 'ปลั๊กอินทั้งหมด'
         */
        function getDiagnosticScopeText(scope) {
            const scopeTexts = {
                'all': 'ทั้งระบบ',
                'plugins': 'ปลั๊กอินทั้งหมด',
                'core': 'ระบบหลัก',
                'dependencies': 'Dependencies',
                'specific': 'ปลั๊กอินที่เลือก'
            };
            return scopeTexts[scope] || 'ไม่ระบุ';
        }
        
        /**
         * ฟังก์ชันอัพเดตข้อความปุ่ม Diagnostic ตาม Scope
         * 
         * @function updateDiagnosticButtonText
         * @param {string} scope - diagnostic scope ที่เลือก
         * @description อัพเดตข้อความของปุ่ม "เริ่มการวินิจฉัย" ให้ตรงกับ scope ที่เลือก
         * 
         * @dependencies
         * - DOM element 'runSystemCheckBtn' -> ปุ่มเริ่มการวินิจฉัย
         * 
         * @calledBy
         * - initParameterizedDiagnostics() -> เมื่อเปลี่ยน scope
         * - Diagnostic scope change event -> อัตโนมัติ
         * 
         * @sideEffects
         * - เปลี่ยน innerHTML ของปุ่ม
         * - เพิ่มไอคอน Font Awesome
         * 
         * @example
         * updateDiagnosticButtonText('all'); // " วินิจฉัยทั้งระบบ"
         * updateDiagnosticButtonText('specific'); // " วินิจฉัยปลั๊กอินที่เลือก"
         */
        function updateDiagnosticButtonText(scope) {
            const button = document.getElementById('runSystemCheckBtn');
            if (!button) return;
            
            const icon = '<i class="fas fa-shield-alt"></i>';
            const texts = {
                'all': `${icon} วินิจฉัยทั้งระบบ`,
                'plugins': `${icon} วินิจฉัยปลั๊กอิน`,
                'core': `${icon} วินิจฉัยระบบหลัก`,
                'dependencies': `${icon} วินิจฉัย Dependencies`,
                'specific': `${icon} วินิจฉัยปลั๊กอินที่เลือก`
            };
            
            button.innerHTML = texts[scope] || `${icon} เริ่มการวินิจฉัย`;
        }

        //  Resize Panel System
        /**
         * คลาสควบคุมระบบ Resize Panel
         * 
         * @class ResizePanelController
         * @description จัดการการ resize panel ระหว่าง terminal section และ sidebar
         * 
         * @property {boolean} isResizing - สถานะว่ากำลัง resize อยู่หรือไม่
         * @property {number} startX - ตำแหน่ง X เริ่มต้นของการ resize
         * @property {number} startWidth - ความกว้างเริ่มต้นของ panel
         * @property {HTMLElement} sidebar - element ของ sidebar
         * @property {HTMLElement} container - element ของ container หลัก
         * @property {HTMLElement} resizeHandle - element ของ resize handle
         * 
         * @dependencies
         * - DOM elements: .terminal-section, .container, #resizeHandle
         * - Mouse/Touch events
         * - CSS styles สำหรับ resizing
         * 
         * @methods
         * - init() -> เริ่มต้นระบบ
         * - initializeResizePanel() -> ตั้งค่า event listeners
         * - startResize() -> เริ่มการ resize
         * - handleResize() -> จัดการขณะ resize
         * - stopResize() -> หยุดการ resize
         * - emergencyCleanup() -> ทำความสะอาดฉุกเฉิน
         * 
         * @features
         * - Mouse drag resize
         * - Keyboard shortcuts (Escape to stop)
         * - Emergency cleanup
         * - Responsive design support
         * 
         * @example
         * const resizeController = new ResizePanelController();
         * // จะเริ่มทำงานอัตโนมัติผ่าน constructor
         */
        class ResizePanelController {
            constructor() {
                this.isResizing = false;
                this.startX = 0;
                this.startWidth = 0;
                this.sidebar = null;
                this.container = null;
                this.resizeHandle = null;
                
                this.init();
            }
            
            init() {
                this.terminalSection = document.querySelector('.terminal-section');
                this.container = document.querySelector('.container');
                this.resizeHandle = document.getElementById('resizeHandle');
                
                if (!this.terminalSection || !this.container || !this.resizeHandle) {
                    console.error(' Resize elements not found');
                    return;
                }
                
                this.initializeResizePanel();
                console.log(' Resize panel system initialized');
            }
            
            initializeResizePanel() {
                // ทำการ bind ฟังก์ชันเก็บไว้ในตัวแปร
                this.boundHandleResize = this.handleResize.bind(this);
                this.boundStopResize = this.stopResize.bind(this);
                
                // เพิ่ม emergency cleanup function
                this.emergencyCleanup = () => {
                    console.log(" Emergency cleanup triggered!");
                    this.stopResize();
                };
                
                // เพิ่ม bound function สำหรับ keydown event
                this.boundKeydownHandler = (event) => {
                    if (event.key === 'Escape') {
                        console.log(" Escape key pressed, stopping resize");
                        this.emergencyCleanup();
                    }
                };
                
                // เมื่อกดเมาส์ลงบนตัวลาก
                this.resizeHandle.addEventListener('mousedown', (e) => {
                    // ป้องกันการทำงานเริ่มต้นของ browser
                    e.preventDefault();
                    e.stopPropagation();
                    
                    console.log(" Mouse down on resize handle");
                    
                    // เพิ่ม event listener ที่ document เพื่อให้ลากได้ทั่วจอ
                    document.addEventListener('mousemove', this.boundHandleResize);
                    document.addEventListener('mouseup', this.boundStopResize);
                    
                    // เพิ่ม emergency cleanup listeners
                    document.addEventListener('mouseleave', this.emergencyCleanup);
                    window.addEventListener('blur', this.emergencyCleanup);
                    document.addEventListener('keydown', this.boundKeydownHandler);
                    
                    // --- เริ่มกระบวนการ Resize ---
                    this.isResizing = true;
                    this.startX = e.clientX;
                    // อ่านค่าความกว้างเริ่มต้นจาก element โดยตรง
                    this.startWidth = this.terminalSection.offsetWidth;
                    
                    // เพิ่มคลาสเพื่อแสดงผลและปิด pointer-events
                    this.container.classList.add('resizing');
                    this.resizeHandle.classList.add('resizing');
                    
                    // เพิ่ม timeout fallback - หากไม่มีการปล่อยเมาส์ภายใน 10 วินาที
                    this.resizeTimeout = setTimeout(() => {
                        console.log(" Resize timeout - forcing cleanup");
                        this.emergencyCleanup();
                    }, 10000);
                });
            }
            
            startResize(e) {
                e.preventDefault();
                e.stopPropagation();
                
                console.log(' Starting resize');
                
                // Add global event listeners
                document.addEventListener('mousemove', this.boundHandleResize);
                document.addEventListener('mouseup', this.boundStopResize);
                document.addEventListener('mouseleave', this.boundEmergencyCleanup);
                window.addEventListener('blur', this.boundEmergencyCleanup);
                
                // Set initial values
                this.isResizing = true;
                this.startX = e.clientX;
                this.startWidth = this.sidebar.offsetWidth;
                
                // Add visual feedback
                this.container.classList.add('resizing');
                this.resizeHandle.classList.add('resizing');
                
                // Safety timeout
                this.resizeTimeout = setTimeout(() => {
                    console.log(' Resize timeout - forcing cleanup');
                    this.emergencyCleanup();
                }, 10000);
            }
            
            handleResize(e) {
                // ถ้าไม่ได้อยู่ในโหมด resizing ก็ไม่ต้องทำอะไร
                if (!this.isResizing) return;
                
                e.preventDefault();
                
                // คำนวณความกว้างใหม่
                const newWidth = this.startWidth + (e.clientX - this.startX);
                
                // กำหนดขอบเขตความกว้าง
                const minWidth = 400;
                const maxWidth = this.container.offsetWidth * 0.75;
                
                // ปรับความกว้างของ terminalSection โดยไม่ให้เกินขอบเขต
                if (newWidth >= minWidth && newWidth <= maxWidth) {
                    this.terminalSection.style.width = newWidth + 'px';
                }
            }
            
            stopResize() {
                console.log(" stopResize() called, current isResizing:", this.isResizing);
                
                // --- การันตีว่าส่วนนี้จะทำงานเสมอ ไม่ว่าจะเกิดอะไรขึ้น ---
                try {
                    // ถ้าไม่ได้อยู่ในโหมด resizing แต่ยังมีคลาส resizing ติดอยู่ ให้ลบออก
                    if (!this.isResizing && this.container.classList.contains('resizing')) {
                        console.log(" Found orphaned resizing class, cleaning up...");
                    }
                    
                    // แสดง notification เมื่อ resize สำเร็จ
                    if (this.isResizing && window.showNotification) {
                        const currentWidth = this.terminalSection.offsetWidth;
                        window.showNotification(` ปรับขนาด Terminal เป็น ${currentWidth}px`, 'success');
                    }
                } catch (error) {
                    console.error("เกิดข้อผิดพลาดระหว่าง resize:", error);
                } finally {
                    // --- การันตีว่าส่วนนี้จะทำงานเสมอ ไม่ว่าจะเกิด Error หรือไม่ ---
                    console.log(" Finally block: Cleaning up resize state...");
                    
                    this.isResizing = false;
                    
                    // นำคลาสที่บล็อกการทำงานออก (บังคับลบ)
                    this.container.classList.remove('resizing');
                    this.resizeHandle.classList.remove('resizing');
                    
                    // ลบ event listener ที่ไม่ต้องการแล้วออกจาก document (บังคับลบ)
                    document.removeEventListener('mousemove', this.boundHandleResize);
                    document.removeEventListener('mouseup', this.boundStopResize);
                    
                    // ลบ emergency cleanup listeners
                    document.removeEventListener('mouseleave', this.emergencyCleanup);
                    window.removeEventListener('blur', this.emergencyCleanup);
                    document.removeEventListener('keydown', this.boundKeydownHandler);
                    
                    // Clear timeout
                    if (this.resizeTimeout) {
                        clearTimeout(this.resizeTimeout);
                        this.resizeTimeout = null;
                    }
                    
                    console.log(" Resizing stopped and ALL listeners cleaned up.");
                }
            }
        }
        
        // Initialize resize controller
        window.resizeController = null;

        //  License Dropdown Functions
        function initializeLicenseDropdown() {
            const licenseDropdown = document.getElementById('licenseDropdown');
            const checkLicenseBtn = document.getElementById('checkLicenseBtn');
            const licenseModalOverlay = document.getElementById('licenseModalOverlay');
            const licenseModalCloseBtn = document.getElementById('licenseModalCloseBtn');

            if (licenseDropdown) {
                const toggleBtn = licenseDropdown.querySelector('.dropdown-toggle');
                const menu = licenseDropdown.querySelector('.dropdown-menu');

                toggleBtn.addEventListener('click', (event) => {
                    event.stopPropagation();
                    menu.classList.toggle('show');
                });

                checkLicenseBtn.addEventListener('click', (event) => {
                    event.preventDefault();
                    checkMyLicense();
                    menu.classList.remove('show');
                });

                // Close dropdown when clicking outside
                window.addEventListener('click', (event) => {
                    if (licenseDropdown && !licenseDropdown.contains(event.target)) {
                        menu.classList.remove('show');
                    }
                });
            }

            // License Modal Event Listeners
            if (licenseModalOverlay) {
                const closeModal = () => licenseModalOverlay.classList.remove('show');
                licenseModalCloseBtn.addEventListener('click', closeModal);
                licenseModalOverlay.addEventListener('click', (event) => {
                    if (event.target === licenseModalOverlay) {
                        closeModal();
                    }
                });
            }

            console.log(' License dropdown initialized');
        }
        
        //  Theme Dropdown Functions
        function initializeThemeDropdown() {
            const themeDropdown = document.getElementById('themeDropdown');
            
            if (themeDropdown) {
                const toggleBtn = themeDropdown.querySelector('.dropdown-toggle');
                const menu = themeDropdown.querySelector('.dropdown-menu');
                
                toggleBtn.addEventListener('click', (event) => {
                    event.stopPropagation();
                    menu.classList.toggle('show');
                });
                
                // Close dropdown when clicking outside
                window.addEventListener('click', (event) => {
                    if (themeDropdown && !themeDropdown.contains(event.target)) {
                        menu.classList.remove('show');
                    }
                });
                
                // Close dropdown when theme is selected
                const themeItems = menu.querySelectorAll('.dropdown-item');
                themeItems.forEach(item => {
                    item.addEventListener('click', () => {
                        menu.classList.remove('show');
                    });
                });
            }
            
            console.log(' Theme dropdown initialized');
        }

        // =====  ENHANCED LICENSE POPUP FUNCTIONS (จาก Chahua License Framework) =====
        
        // แสดงป๊อปอัพไลเซนส์ขั้นสูง
        /**
         * ฟังก์ชันแสดง License Popup (จะถูก DEPRECATED)
         * 
         * @function showLicensePopup
         * @async
         * @param {string} title - หัวข้อ popup
         * @param {string} message - ข้อความใน popup
         * @param {string} [type='info'] - ประเภทของ popup (info, warning, error)
         * @description แสดง License Popup แบบ Modal
         * @deprecated ฟังก์ชันนี้จะไม่ถูกใช้งานแล้ว
         * 
         * @returns {Promise<void>}
         * 
         * @calledBy License functions ต่างๆ
         */
        async function showLicensePopup(title, message, type = 'info') {
            try {
                if (window.electronAPI && window.electronAPI.showLicensePopup) {
                    const result = await window.electronAPI.showLicensePopup(title, message, type);
                    console.log(' License popup result:', result);
                    return result;
                } else {
                    // Fallback to alert
                    alert(`${title}\n\n${message}`);
                    return { success: true, method: 'fallback' };
                }
            } catch (error) {
                console.error(' Error showing license popup:', error);
                alert(`Error: ${title}\n\n${message}`);
                return { success: false, error: error.message };
            }
        }

        // แสดงสถานะไลเซนส์แบบป๊อปอัพใหม่
        async function showLicenseStatusPopup() {
            try {
                const status = await window.electronAPI.getLicenseStatus();
                
                if (status && status.success) {
                    const data = status.data;
                    const message = `ประเภทไลเซนส์: ${data.type || 'ไม่ระบุ'}\n` +
                                  `สถานะ: ${data.message || 'ใช้งานได้'}\n` +
                                  `วันที่สร้าง: ${data.generatedAt ? new Date(data.generatedAt).toLocaleString('th-TH') : 'ไม่ระบุ'}\n` +
                                  `เวลาคงเหลือ: ${data.daysRemaining > 365 ? 'ไม่จำกัด' : data.daysRemaining + ' วัน'}\n` +
                                  `รหัส License: ${data.licenseId || 'AUTO-GENERATED'}`;
                    
                    await showLicensePopup(' ข้อมูลสถานะไลเซนส์', message, 'info');
                    addTerminalLine(` License Status: ${data.type} (${data.status})`, 'success');
                } else {
                    await showLicensePopup(' ข้อผิดพลาดไลเซนส์', status.error || 'ไม่สามารถตรวจสอบสถานะไลเซนส์ได้', 'error');
                    addTerminalLine(` License Error: ${status.error || 'ไม่พบ License'}`, 'error');
                }
            } catch (error) {
                await showLicensePopup(' ข้อผิดพลาดระบบ', `เกิดข้อผิดพลาดในการตรวจสอบไลเซนส์:\n${error.message}`, 'error');
                addTerminalLine(` ข้อผิดพลาดในการตรวจสอบ License: ${error.message}`, 'error');
            }
        }

        // แสดงช่วยเหลือการ Activate License
        async function showLicenseActivationHelp() {
            const helpMessage = ` วิธีการ Activate License:\n\n` +
                              `1.  ติดต่อ: chahuadev@gmail.com\n` +
                              `2.  เยี่ยมชม: www.chahuadev.com\n` +
                              `3.  แฟนเพจ: Chahua Development Thailand\n\n` +
                              ` สำหรับการสนับสนุนและขอไลเซนส์`;
            
            await showLicensePopup(' ช่วยเหลือการ Activate License', helpMessage, 'info');
        }

        // ทดสอบป๊อปอัพแต่ละประเภท
        async function testLicensePopups() {
            console.log(' เริ่มทดสอบระบบป๊อปอัพ License...');
            addTerminalLine(' เริ่มทดสอบระบบป๊อปอัพ License...', 'info');
            
            await showLicensePopup(' ทดสอบ Info', 'นี่คือป๊อปอัพแสดงข้อมูลทั่วไป\nระบบทำงานปกติ', 'info');
            
            setTimeout(async () => {
                await showLicensePopup(' ทดสอบ Success', 'นี่คือป๊อปอัพแสดงความสำเร็จ\nการทำงานสำเร็จลุล่วง', 'success');
            }, 1500);
            
            setTimeout(async () => {
                await showLicensePopup(' ทดสอบ Warning', 'นี่คือป๊อปอัพแสดงคำเตือน\nกรุณาตรวจสอบระบบ', 'warning');
            }, 3000);
            
            setTimeout(async () => {
                await showLicensePopup(' ทดสอบ Error', 'นี่คือป๊อปอัพแสดงข้อผิดพลาด\nระบบพบปัญหาบางอย่าง', 'error');
                addTerminalLine(' ทดสอบระบบป๊อปอัพเสร็จสิ้น', 'success');
            }, 4500);
        }

        // แสดงข้อมูลเวอร์ชันของระบบ License Framework
        async function showLicenseSystemInfo() {
            const systemInfo = ` Chahua License Framework v3.0\n\n` +
                             ` Integration: Chahuadev Framework\n` +
                             ` Security: Validation Gateway\n` +
                             ` Protection: Hardware Fingerprint Binding\n` +
                             ` Performance: Zero External Dependencies\n` +
                             ` Architecture: Electron + Node.js\n\n` +
                             ` Chahua Development Thailand\n` +
                             ` CEO: Saharath C.\n` +
                             ` Website: www.chahuadev.com\n` +
                             ` Email: chahuadev@gmail.com`;
            
            await showLicensePopup(' ข้อมูลระบบ License Framework', systemInfo, 'info');
        }

        // เมนูสำหรับผู้พัฒนา (Developer Menu)
        function showDeveloperLicenseMenu() {
            const choice = prompt(` Developer License Tools:\n\n` +
                                `1. ทดสอบป๊อปอัพทุกประเภท\n` +
                                `2. แสดงข้อมูลระบบ License\n` +
                                `3. ตรวจสอบสถานะ License (Popup)\n` +
                                `4. แสดงช่วยเหลือ Activation\n\n` +
                                `เลือกหมายเลข (1-4):`);
            
            switch(choice) {
                case '1':
                    testLicensePopups();
                    break;
                case '2':
                    showLicenseSystemInfo();
                    break;
                case '3':
                    showLicenseStatusPopup();
                    break;
                case '4':
                    showLicenseActivationHelp();
                    break;
                default:
                    if (choice !== null) {
                        alert(' กรุณาเลือกหมายเลข 1-4');
                    }
            }
        }

        //  License Checking Function (อัปเกรดให้ใช้ป๊อปอัพแทน Modal)
        async function checkMyLicense() {
            // ใช้ระบบป๊อปอัพใหม่แทน modal เดิม
            await showLicenseStatusPopup();
        }

        // ---  View Switcher Logic ---
        document.addEventListener('DOMContentLoaded', () => {
            const logPanel = document.getElementById('log-viewer');
            const marketplacePanel = document.getElementById('marketplace-webview');

            // URL ของร้านค้าบนเว็บไซต์ของคุณ
            const marketplaceUrl = 'https://chahuadev.com'; // <--  แก้ไขเป็น URL ของคุณ

            let isMarketplaceLoaded = false;

            function switchView(viewToShow) {
                // ซ่อน Panel ทั้งหมดและเอา active class ออกจากปุ่ม
                document.querySelectorAll('.view-panel').forEach(p => p.classList.remove('active'));
                document.querySelectorAll('.view-btn').forEach(b => b.classList.remove('active'));

                // แสดง Panel และปุ่มที่เลือก
                if (viewToShow === 'log') {
                    if (logPanel) logPanel.classList.add('active');
                } else if (viewToShow === 'marketplace') {
                    if (marketplacePanel) marketplacePanel.classList.add('active');

                    // โหลด URL ของร้านค้าแค่ครั้งแรกที่กด
                    if (!isMarketplaceLoaded && marketplacePanel) {
                        addTerminalLine(`กำลังเชื่อมต่อกับร้านค้าที่ ${marketplaceUrl}...`, 'command');
                        marketplacePanel.src = marketplaceUrl;
                        isMarketplaceLoaded = true;

                        marketplacePanel.addEventListener('did-finish-load', () => {
                             addTerminalLine(' เชื่อมต่อร้านค้าสำเร็จ!', 'success');
                        });
                        marketplacePanel.addEventListener('did-fail-load', (error) => {
                             addTerminalLine(` ไม่สามารถเชื่อมต่อร้านค้าได้: ${error.errorDescription}`, 'error');
                        });
                    }
                }
            }

            // เพิ่ม switchView ให้เป็น global function เพื่อให้ Top Nav ใช้ได้
            window.switchView = switchView;
        });

        //  ทำความสะอาด Event Listeners เมื่อปิดหน้าต่าง
        window.addEventListener('beforeunload', () => {
            if (window.electronAPI && window.electronAPI.removeBuildLogListeners) {
                window.electronAPI.removeBuildLogListeners();
            }
        });