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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import json
import importlib
import requests
import gradio as gr
import subprocess

class Tool:
    def __init__(self, name, description, ui_class, icon="🔧", version="0.1", ui_module=None):
        self.name = name
        self.description = description
        self.ui_class = ui_class
        self.icon = icon
        self.version = version
        self.ui_module = ui_module

class MainUI:
    def __init__(self):
        # Load installed tools from JSON
        self.tools = {}
        self.load_installed_tools()
        
        # Marketplace server URL
        self.marketplace_url = "https://marketplace.vidplus.app/api/marketplace"
        self.version = "0.1"
        
        # Create tools directory if it doesn't exist
        os.makedirs('tools', exist_ok=True)

    def load_installed_tools(self):
        """Load installed tools from JSON file"""
        try:
            if os.path.exists('installed_tools.json'):
                with open('installed_tools.json', 'r') as f:
                    data = json.load(f)
                    
                for tool_data in data.get('tools', []):
                    # If ui_module is specified, dynamically import it
                    if tool_data.get('ui_module'):
                        try:
                            module = importlib.import_module(tool_data['ui_module'])
                            ui_class = getattr(module, tool_data['ui_class'])
                            
                            self.tools[tool_data['id']] = Tool(
                                name=tool_data['name'],
                                description=tool_data['description'],
                                ui_class=ui_class,
                                icon=tool_data['icon'],
                                version=tool_data['version'],
                                ui_module=tool_data['ui_module']
                            )
                        except (ImportError, AttributeError) as e:
                            print(f"Error loading tool {tool_data['name']}: {e}")
        except Exception as e:
            print(f"Error loading installed tools: {e}")
            # Fallback to default BeatSyncer tool
            # self.tools = {
            #     "beatsyncer": Tool(
            #         name="BeatSyncer",
            #         description="Create amazing videos synchronized with music beats",
            #         ui_class=BeatSyncerUI,
            #         icon="🎵"
            #     )
            # }

    def save_installed_tools(self):
        """Save installed tools to JSON file"""
        data = {
            "tools": [
                {
                    "id": tool_id,
                    "name": tool.name,
                    "description": tool.description,
                    "icon": tool.icon,
                    "version": tool.version,
                    "ui_class": tool.ui_class.__name__,
                    "ui_module": tool.ui_module
                }
                for tool_id, tool in self.tools.items()
            ]
        }
        
        with open('installed_tools.json', 'w') as f:
            json.dump(data, f, indent=4)

    def fetch_marketplace_tools(self):
        """Fetch available tools from marketplace server"""
        try:
            response = requests.get(f"{self.marketplace_url}/tools")
            if response.status_code == 200:
                # Get the list of tools from the marketplace
                marketplace_tools = response.json()
                
                # Ensure we're working with the latest state of installed tools
                # This is important after a tool has been removed
                if os.path.exists('installed_tools.json'):
                    with open('installed_tools.json', 'r') as f:
                        data = json.load(f)
                        installed_tool_ids = [tool['id'] for tool in data.get('tools', [])]
                else:
                    installed_tool_ids = []
                
                # Update the is_installed flag for each tool
                for tool in marketplace_tools:
                    tool['is_installed'] = tool['id'] in installed_tool_ids
                
                return marketplace_tools
            else:
                return []
        except Exception as e:
            print(f"Error fetching marketplace tools: {e}")
            return []

    def fetch_tool_details(self, tool_id):
        """Fetch details for a specific tool from marketplace server"""
        try:
            response = requests.get(f"{self.marketplace_url}/tools/{tool_id}")
            if response.status_code == 200:
                return response.json()
            else:
                return None
        except Exception as e:
            print(f"Error fetching tool details: {e}")
            return None

    def install_tool(self, tool_id):
        """Install a tool from the marketplace"""
        try:
            # Import required modules
            import importlib
            import importlib.util
            import sys
            import subprocess
            import gradio as gr
            
            # Fetch tool data
            response = requests.get(f"{self.marketplace_url}/tools/{tool_id}/download")
            if response.status_code != 200:
                return f"Error: Failed to download tool (Status code: {response.status_code})"
            
            tool_data = response.json()
            tool_info = tool_data['tool']
            tool_files = tool_data['files']
            
            # Check and install dependencies if they exist
            dependencies = tool_info.get('dependencies', [])
            if dependencies:
                try:
                    # Read current requirements.txt
                    current_requirements = []
                    if os.path.exists('requirements.txt'):
                        with open('requirements.txt', 'r') as f:
                            current_requirements = [line.strip() for line in f.readlines() if line.strip()]
                    
                    # Check which dependencies need to be installed
                    to_install = []
                    to_add_to_requirements = []
                    
                    for dep in dependencies:
                        # Extract just the package name (ignore version requirements)
                        pkg_name = dep.split('>=')[0].split('==')[0].split('>')[0].split('<')[0].strip()
                        
                        # Check if dependency is already in requirements.txt
                        is_in_requirements = False
                        for req in current_requirements:
                            req_name = req.split('>=')[0].split('==')[0].split('>')[0].split('<')[0].strip()
                            if req_name == pkg_name:
                                is_in_requirements = True
                                break
                        
                        if not is_in_requirements:
                            to_add_to_requirements.append(dep)
                        
                        try:
                            # Try to import the package to check if it's installed
                            importlib.import_module(pkg_name)
                        except ImportError:
                            # Package not installed, add to installation list
                            to_install.append(dep)
                    
                    # Install missing dependencies
                    if to_install:
                        for dep in to_install:
                            # Use subprocess to run pip install
                            subprocess.check_call([sys.executable, "-m", "pip", "install", dep])
                    
                    # Append new dependencies to requirements.txt
                    if to_add_to_requirements:
                        with open('requirements.txt', 'a') as f:
                            for dep in to_add_to_requirements:
                                f.write(f"\n{dep}")
                        print(f"Added {len(to_add_to_requirements)} dependencies to requirements.txt")
                        
                except Exception as e:
                    return f"Error installing dependencies: {e}"
            
            # Create tool directory
            tool_dir = os.path.join('tools', tool_id)
            os.makedirs(tool_dir, exist_ok=True)
            
            # Write tool files
            for file_name, file_content in tool_files.items():
                # Rename files to match our convention
                target_file_name = file_name
                if file_name.endswith('_tool_logic.py'):
                    target_file_name = f"{tool_id}_tool.py"
                elif file_name.endswith('_tool_ui.py'):
                    target_file_name = f"{tool_id}_ui.py"
                
                with open(os.path.join(tool_dir, target_file_name), 'w') as f:
                    f.write(file_content)
            
            # Create __init__.py to make the directory a package
            with open(os.path.join(tool_dir, '__init__.py'), 'w') as f:
                f.write(f"# {tool_info['name']} package\n")
            
            # Add tool to installed tools
            ui_module = f"tools.{tool_id}.{tool_id}_ui"
            ui_class = f"{tool_id.title().replace('_', '')}UI"
            
            # Update installed_tools.json
            with open('installed_tools.json', 'r') as f:
                data = json.load(f)
            
            data['tools'].append({
                "id": tool_id,
                "name": tool_info['name'],
                "description": tool_info['description'],
                "icon": tool_info['icon'],
                "version": tool_info['version'],
                "ui_class": ui_class,
                "ui_module": ui_module
            })
            
            with open('installed_tools.json', 'w') as f:
                json.dump(data, f, indent=4)
            
            # Dynamically load the newly installed tool
            try:
                # Reload the module if it was already imported
                if ui_module in sys.modules:
                    importlib.reload(sys.modules[ui_module])
                
                # Import the module
                module = importlib.import_module(ui_module)
                ui_class_obj = getattr(module, ui_class)
                
                # Add the tool to self.tools
                self.tools[tool_id] = Tool(
                    name=tool_info['name'],
                    description=tool_info['description'],
                    ui_class=ui_class_obj,
                    icon=tool_info['icon'],
                    version=tool_info['version'],
                    ui_module=ui_module
                )
                
                # Flag to indicate this is a newly installed tool that needs special handling
                self.tools[tool_id].newly_installed = True
                
                # Return success message
                return f"Successfully installed {tool_info['name']}. The tool is now available in the Tools page."
            except Exception as e:
                print(f"Error dynamically loading tool: {e}")
                import traceback
                traceback.print_exc()
                # Still return success but with a restart message
                return f"Successfully installed {tool_info['name']}. Please restart the application to use the new tool."
        except Exception as e:
            return f"Error installing tool: {e}"

    def remove_tool(self, tool_id):
        """Remove an installed tool"""
        try:
            if tool_id not in self.tools:
                return "Error: Tool is not installed"
            
            # Get tool info before removal
            tool_name = self.tools[tool_id].name
            
            # Remove tool directory
            tool_dir = os.path.join('tools', tool_id)
            if os.path.exists(tool_dir):
                import shutil
                shutil.rmtree(tool_dir)
                print(f"Removed tool directory: {tool_dir}")
            
            # Remove tool from installed_tools.json
            if os.path.exists('installed_tools.json'):
                with open('installed_tools.json', 'r') as f:
                    data = json.load(f)
                
                # Filter out the tool to be removed
                data['tools'] = [tool for tool in data['tools'] if tool['id'] != tool_id]
                
                # Save updated tools list
                with open('installed_tools.json', 'w') as f:
                    json.dump(data, f, indent=4)
                
                print(f"Removed tool from installed_tools.json: {tool_id}")
            
            # Remove tool from self.tools
            del self.tools[tool_id]
            
            return f"✅ Successfully removed {tool_name}"
        except Exception as e:
            print(f"Error removing tool: {e}")
            import traceback
            traceback.print_exc()
            return f"Error removing tool: {str(e)}"

    def create_tool_card(self, name):
        return f"""
            <div style="
                background: #E6E6E6;
                border-radius: 16px;
                width: 200px;
                height: 200px;
                display: flex;
                justify-content: center;
                align-items: center;
                cursor: pointer;
                transition: transform 0.2s;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                &:hover {{
                    transform: scale(1.02);
                }}">
                <span style="color: #1a1a1a; font-size: 16px; font-weight: 500;">{name}</span>
            </div>
        """

    def create_ui(self):
        css = """
        :root {
            --sidebar-width: 200px;
        }
        
        body {
            margin: 0;
            padding: 0;
            overflow: hidden;
        }
        
        #sidebar {
            background-color: #0A192F;
            color: white;
            padding: 32px 24px;
            height: 100vh;
            width: var(--sidebar-width);
            position: fixed;
            left: 0;
            top: 0;
            display: flex;
            flex-direction: column;
            box-sizing: border-box;
            z-index: 1000;
        }
        
        #main-content {
            background-color: #0F172A;
            min-height: 100vh;
            margin-left: var(--sidebar-width);
            padding: 50px;
            box-sizing: border-box;
            overflow-y: auto;
            position: relative;
            max-height: 100vh; /* Ensure content is scrollable */
        }
        
        .nav-button {
            background: none !important;
            border: none !important;
            box-shadow: none !important;
            color: #94A3B8 !important;
            padding: 8px 0 !important;
            margin: 4px 0 !important;
            min-width: unset !important;
            width: 100% !important;
            text-align: left !important;
            font-size: 16px !important;
            font-weight: 500 !important;
            height: auto !important;
            line-height: 1.2 !important;
        }
        
        .nav-button:hover {
            color: white !important;
        }
        
        .nav-button[variant="primary"] {
            color: white !important;
        }
        
        .tool-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 20px;
            padding: 24px 0;
            width: 100%;
        }
        
        .version-text {
            margin-top: auto;
            color: #64748B;
            font-size: 12px;
            padding-top: 16px;
        }
        
        .title {
            font-size: 32px;
            font-weight: 800;
            margin-bottom: 32px;
            color: white;
            letter-spacing: -0.5px;
        }
        
        .page-title {
            font-size: 28px;
            font-weight: 700;
            color: white;
            margin: 0;
            padding: 0;
            letter-spacing: -0.5px;
        }
        
        #content-wrapper {
            width: 100%;
            max-width: 100%;
            padding: 24px;
        }
        
        .tool-card {
            background: #1E293B !important;
            border: none !important;
            border-radius: 16px !important;
            overflow: hidden !important;
            transition: transform 0.2s !important;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1) !important;
            height: 100% !important;
            display: flex !important;
            flex-direction: column !important;
            width: auto !important;
            min-height: 200px !important;
            justify-content: flex-start !important;
            align-items: stretch !important;
            padding: 0 !important;
            color: white !important;
            text-align: left !important;
            cursor: pointer !important;
        }
        
        .tool-card:hover {
            transform: scale(1.02) !important;
        }
        
        .tool-card-img {
            width: 100%;
            height: 150px;
            background: #2D3748;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 48px;
            color: #38BDF8;
        }
        
        .tool-card-content {
            padding: 16px !important;
            flex-grow: 1 !important;
            display: flex !important;
            flex-direction: column !important;
        }
        
        .tool-card-title {
            font-size: 18px !important;
            font-weight: 600 !important;
            color: white !important;
            margin: 0 0 8px 0 !important;
        }
        
        .tool-card-description {
            font-size: 14px !important;
            color: #94A3B8 !important;
            margin: 0 !important;
            flex-grow: 1 !important;
        }
        
        .installed-indicator {
            background-color: #10B981 !important;
            color: white !important;
            font-size: 12px !important;
            font-weight: 600 !important;
            padding: 4px 8px !important;
            border-radius: 4px !important;
            margin-top: 8px !important;
            display: inline-block !important;
        }
        
        .tool-card.installed {
            border: 2px solid #10B981 !important;
        }
        
        .add-tool-card {
            background: rgba(255, 255, 255, 0.05) !important;
            border: 2px dashed rgba(255, 255, 255, 0.2) !important;
            color: rgba(255, 255, 255, 0.8) !important;
            display: flex !important;
            flex-direction: column !important;
            justify-content: center !important;
            align-items: center !important;
            text-align: center !important;
            padding: 16px !important;
        }
        
        .add-tool-icon {
            font-size: 32px;
            margin-bottom: 16px;
            color: rgba(255, 255, 255, 0.5);
        }
        
        .tool-card-button {
            background: transparent !important;
            border: none !important;
            padding: 0 !important;
            margin: 0 !important;
            width: 100% !important;
            height: auto !important;
            min-height: 0 !important;
            box-shadow: none !important;
        }
        
        .tool-details {
            width: 100%;
            max-width: 100%;
            padding: 0;
        }
        
        .tool-details-container {
            background: #0F172A;
            border-radius: 0;
            padding: 32px;
            margin-bottom: 0;
            max-height: 100vh;
            overflow-y: auto;
            width: 100%;
        }
        
        .tool-details-header {
            display: flex;
            align-items: center;
            margin-bottom: 24px;
            justify-content: space-between;
        }
        
        .tool-details-title-section {
            display: flex;
            align-items: center;
        }
        
        .tool-details-icon {
            font-size: 28px;
            margin-right: 16px;
        }
        
        .tool-details-title {
            font-size: 28px;
            font-weight: 700;
            color: white;
            margin: 0;
        }
        
        .tool-details-version {
            font-size: 14px;
            color: #94A3B8;
            margin-left: 8px;
        }
        
        .tool-details-description {
            font-size: 16px;
            color: #E2E8F0;
            margin-bottom: 32px;
            max-width: 800px;
        }
        
        .tool-details-section-title {
            font-size: 18px;
            font-weight: 600;
            color: white;
            margin: 32px 0 16px 0;
        }
        
        .tool-details-features {
            display: flex;
            flex-direction: column;
            gap: 12px;
            margin-bottom: 32px;
        }
        
        .tool-details-feature {
            display: flex;
            align-items: center;
            margin-bottom: 0;
        }
        
        .tool-details-feature-icon {
            color: #38BDF8;
            margin-right: 12px;
            font-size: 16px;
        }
        
        .tool-details-feature-text {
            color: #E2E8F0;
            font-size: 16px;
        }
        
        .tool-details-screenshots {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 16px;
            margin-top: 16px;
        }
        
        .tool-details-screenshot {
            width: 100%;
            border-radius: 8px;
            overflow: hidden;
        }
        
        .tool-details-video {
            width: 100%;
            aspect-ratio: 16/9;
            border-radius: 8px;
            overflow: hidden;
            margin-top: 16px;
            background: #1E293B;
            border: none;
            max-width: 800px;
            height: 450px;
        }
        
        .back-button {
            background: transparent !important;
            border: none !important;
            color: #94A3B8 !important;
            font-size: 14px !important;
            padding: 8px 16px !important;
            border-radius: 8px !important;
            cursor: pointer !important;
            transition: background-color 0.2s !important;
            text-align: left !important;
            width: auto !important;
            margin-bottom: 24px !important;
        }
        
        .back-button:hover {
            background: rgba(255, 255, 255, 0.1) !important;
        }
        
        .install-button {
            background: #38BDF8 !important;
            color: #0F172A !important;
            font-weight: 600 !important;
            padding: 12px 24px !important;
            border-radius: 8px !important;
            margin-top: 24px !important;
            width: 100% !important;
        }
        
        .install-button:hover {
            background: #0EA5E9 !important;
        }
        
        .remove-button {
            background: #EF4444 !important;
            color: white !important;
            font-weight: 600 !important;
            padding: 12px 24px !important;
            border-radius: 8px !important;
            margin-top: 24px !important;
            width: 100% !important;
            border: none !important;
            cursor: pointer !important;
            transition: background-color 0.2s !important;
        }
        
        .remove-button:hover {
            background: #DC2626 !important;
        }
        
        .tool-details-action .remove-button {
            margin-top: 0 !important;
            padding: 8px 16px !important;
            font-size: 14px !important;
            width: auto !important;
        }
        
        /* Confirmation dialog styling */
        .confirmation-dialog {
            background-color: #1E293B;
            border-radius: 8px;
            padding: 24px;
            margin-bottom: 24px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
            border: 1px solid #2D3748;
        }
        
        .confirmation-title {
            font-size: 18px;
            font-weight: 600;
            color: white;
            margin-bottom: 16px;
        }
        
        .confirmation-message {
            font-size: 14px;
            color: #E2E8F0;
            margin-bottom: 24px;
        }
        
        .confirmation-buttons {
            display: flex;
            justify-content: flex-end;
            gap: 12px;
        }
        
        .cancel-button {
            background: #4B5563 !important;
            color: white !important;
            font-weight: 600 !important;
            padding: 8px 16px !important;
            border-radius: 8px !important;
            border: none !important;
            cursor: pointer !important;
            transition: background-color 0.2s !important;
        }
        
        .cancel-button:hover {
            background: #374151 !important;
        }
        
        .confirm-button {
            background: #EF4444 !important;
            color: white !important;
            font-weight: 600 !important;
            padding: 8px 16px !important;
            border-radius: 8px !important;
            border: none !important;
            cursor: pointer !important;
            transition: background-color 0.2s !important;
        }
        
        .confirm-button:hover {
            background: #DC2626 !important;
        }
        
        /* Modal styling */
        #installation-modal {
            max-width: 500px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
        
        #installation-status {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 12px;
            padding-bottom: 8px;
            border-bottom: 1px solid #e5e7eb;
        }
        
        #installation-result {
            font-size: 14px;
            margin-bottom: 20px;
            white-space: pre-wrap;
            max-height: 300px;
            overflow-y: auto;
        }
        
        #close-modal-btn {
            background-color: #6B7280;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-weight: 500;
            transition: background-color 0.2s;
            margin-top: 12px;
        }
        
        #close-modal-btn:hover {
            background-color: #4B5563;
        }
        
        /* Installation result styling */
        #installation-result-container {
            margin-bottom: 20px;
            border: 1px solid #2D3748;
            border-radius: 8px;
            padding: 16px;
            background-color: #1E293B;
            max-width: 100%;
            position: relative;
            z-index: 100;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
            margin-top: 0;
        }
        
        #installation-status {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 12px;
            padding-bottom: 8px;
            border-bottom: 1px solid #2D3748;
        }
        
        #installation-result {
            font-size: 14px;
            margin-bottom: 20px;
            white-space: pre-wrap;
            max-height: 300px;
            overflow-y: auto;
        }
        
        #close-result-btn {
            background-color: #6B7280;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-weight: 500;
            transition: background-color 0.2s;
            margin-top: 12px;
        }
        
        #close-result-btn:hover {
            background-color: #4B5563;
        }
        
        .tool-details-action {
            display: flex;
            align-items: center;
        }
        
        .tool-details-action .install-button {
            margin-top: 0 !important;
            padding: 8px 16px !important;
            font-size: 14px !important;
            width: auto !important;
        }
        """

        with gr.Blocks(theme=gr.themes.Default(), css=css) as app:
            # Define state variables
            marketplace_tools_state = gr.State([])
            current_tool_details_state = gr.State(None)

            # Define event handlers first, before any references to them
            def show_tools():
                # Create updates to hide all tool containers
                tool_container_updates = [gr.update(visible=False) for _ in tool_containers]
                
                # Generate fresh HTML for tools grid based on current tools
                tools_html = ''
                for tool_id, tool in self.tools.items():
                    # Create HTML for each tool card
                    tools_html += f'''
                    <div class="tool-card" id="tool-card-{tool_id}" onclick="document.getElementById('tool-btn-{tool_id}').click()">
                        <div class="tool-card-img">
                            {tool.icon}
                        </div>
                        <div class="tool-card-content">
                            <h3 class="tool-card-title">{tool.name}</h3>
                            <p class="tool-card-description">{tool.description if hasattr(tool, 'description') else ""}</p>
                        </div>
                    </div>
                    '''
                
                # Add "Add New Tool" button
                tools_html += '''
                <div class="tool-card add-tool-card" onclick="document.getElementById('add-tool-btn').click()">
                    <div class="add-tool-icon">+</div>
                    <div>Add New Tool from Marketplace</div>
                </div>
                '''
                
                # Create HTML update for tools grid
                tools_html_component = gr.HTML(f'<div class="tool-grid">{tools_html}</div>')
                
                return [
                    gr.update(visible=True),   # tools_content
                    gr.update(visible=False),  # marketplace_content
                    gr.update(visible=False),  # settings_content
                    gr.update(visible=False),  # tool_interfaces
                    gr.update(visible=False),  # tool_details_content
                    gr.update(variant="primary"),    # tools_btn
                    gr.update(variant="secondary"),  # marketplace_btn
                    gr.update(variant="secondary"),  # settings_btn,
                    tools_html_component,  # tools_html_component
                    gr.update(value="")  # tool_interfaces_html
                ] + tool_container_updates
            
            def show_marketplace():
                # Fetch marketplace tools
                tools = self.fetch_marketplace_tools()
                
                # Create HTML for marketplace grid
                html = '<div class="tool-grid">'
                
                for i, tool in enumerate(tools):
                    # Use a unique ID for each card based on the tool ID
                    # Add a class to indicate if the tool is installed
                    installed_class = "installed" if tool.get('is_installed', False) else ""
                    
                    # Add an indicator for installed tools
                    installed_indicator = '<div class="installed-indicator">✓ Installed</div>' if tool.get('is_installed', False) else ''
                    
                    html += f'''
                    <div class="tool-card {installed_class}" id="card-{tool['id']}" onclick="document.getElementById('marketplace-tool-btn-{i}').click()">
                        <div class="tool-card-img">
                            {tool['icon']}
                        </div>
                        <div class="tool-card-content">
                            <h3 class="tool-card-title">{tool['name']}</h3>
                            <p class="tool-card-description">{tool['description']}</p>
                            {installed_indicator}
                        </div>
                    </div>
                    '''
                
                html += '</div>'
                
                # Hide installation result container and confirmation dialog
                installation_result_container_update = gr.update(visible=False)
                confirmation_dialog_update = gr.update(visible=False)
                
                # Create updates for all tool containers
                tool_container_updates = [gr.update(visible=False) for _ in tool_containers]
                
                # Update marketplace_tools_state with the latest tools
                # This ensures the marketplace shows the current state of available tools
                
                return [
                    gr.update(visible=False),  # tools_content
                    gr.update(visible=True),   # marketplace_content
                    gr.update(visible=False),  # settings_content
                    gr.update(visible=False),  # tool_interfaces
                    gr.update(visible=False),  # tool_details_content
                    gr.update(variant="secondary"),  # tools_btn
                    gr.update(variant="primary"),    # marketplace_btn
                    gr.update(variant="secondary"),  # settings_btn
                    tools,  # marketplace_tools_state - updated with latest tools
                    html,   # marketplace_html
                    installation_result_container_update,  # installation_result_container
                    confirmation_dialog_update,  # confirmation_dialog
                    gr.update(value="")  # tool_interfaces_html
                ] + tool_container_updates
            
            def show_settings():
                # Create updates to hide all tool containers
                tool_container_updates = [gr.update(visible=False) for _ in tool_containers]
                
                return [
                    gr.update(visible=False),  # tools_content
                    gr.update(visible=False),  # marketplace_content
                    gr.update(visible=True),   # settings_content
                    gr.update(visible=False),  # tool_interfaces
                    gr.update(visible=False),  # tool_details_content
                    gr.update(variant="secondary"),  # tools_btn
                    gr.update(variant="secondary"),  # marketplace_btn
                    gr.update(variant="primary"),    # settings_btn
                    gr.update(value="")  # tool_interfaces_html
                ] + tool_container_updates
            
            def show_tool(tool_id=None):
                # Import gradio at the beginning of the function
                import gradio as gr
                
                # Check if the tool exists
                if tool_id not in self.tools:
                    print(f"Tool {tool_id} not found")
                    return show_tools()
                
                # Get the tool
                tool = self.tools[tool_id]
                
                # Check if this is a newly installed tool that needs special handling
                if hasattr(tool, 'newly_installed') and tool.newly_installed:
                    print(f"Dynamically creating UI for newly installed tool: {tool_id}")
                    
                    try:
                        # Create a message to inform the user that we're loading the tool
                        loading_message = f"""
                        <div style="text-align: center; padding: 20px;">
                            <h2>Loading {tool.name}...</h2>
                            <p>Please wait while we set up the tool interface.</p>
                        </div>
                        """
                        
                        # First, return a loading message
                        loading_updates = [
                            gr.update(visible=False),  # tools_content
                            gr.update(visible=False),  # marketplace_content
                            gr.update(visible=False),  # settings_content
                            gr.update(visible=True),   # tool_interfaces
                            gr.update(visible=False),  # tool_details_content
                            gr.update(variant="secondary"),  # tools_btn
                            gr.update(variant="secondary"),  # marketplace_btn
                            gr.update(variant="secondary"),  # settings_btn
                            gr.update(value=loading_message)  # tool_interfaces_html
                        ] + [gr.update(visible=False) for _ in tool_containers]
                        
                        # Instead of trying to create the UI dynamically, which can cause issues with Gradio components,
                        # we'll create a simple HTML interface that provides basic functionality and instructions
                        
                        # Get the tool class name and module for display
                        tool_class_name = tool.ui_class.__name__
                        tool_module_name = tool.ui_module
                        
                        # Create a friendly HTML interface
                        tool_html = f"""
                        <div style="text-align: center; padding: 20px;">
                            <h2>{tool.name} is Ready!</h2>
                            <p>This tool has been successfully installed.</p>
                            <p>For the best experience with this tool, please restart the application.</p>
                            <p>After restarting, you'll be able to use all the features of this tool.</p>
                            <!--<div style="margin-top: 20px;">
                                <button onclick="window.location.reload()" style="background-color: #4CAF50; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; font-size: 16px;">Refresh Page</button>
                            </div>-->
                        </div>
                        """
                        
                        # Remove the newly_installed flag so we don't try to create the UI again
                        delattr(tool, 'newly_installed')
                        
                        # Return the HTML interface
                        return [
                            gr.update(visible=False),  # tools_content
                            gr.update(visible=False),  # marketplace_content
                            gr.update(visible=False),  # settings_content
                            gr.update(visible=True),   # tool_interfaces
                            gr.update(visible=False),  # tool_details_content
                            gr.update(variant="secondary"),  # tools_btn
                            gr.update(variant="secondary"),  # marketplace_btn
                            gr.update(variant="secondary"),  # settings_btn
                            gr.update(value=tool_html)  # tool_interfaces_html
                        ] + [gr.update(visible=False) for _ in tool_containers]
                    except Exception as e:
                        print(f"Error creating UI for newly installed tool: {e}")
                        import traceback
                        traceback.print_exc()
                        
                        # If there's an error, show a message asking the user to restart
                        restart_message = f"""
                        <div style="text-align: center; padding: 20px;">
                            <h2>Error Loading {tool.name}</h2>
                            <p>There was an error setting up the tool interface:</p>
                            <pre style="text-align: left; background: #f0f0f0; padding: 10px; border-radius: 5px; overflow: auto;">{str(e)}</pre>
                            <p>Please restart the application to use this tool.</p>
                            <div style="margin-top: 20px;">
                                <button onclick="window.location.reload()" style="background-color: #4CAF50; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; font-size: 16px;">Refresh Page</button>
                            </div>
                        </div>
                        """
                        
                        return [
                            gr.update(visible=False),  # tools_content
                            gr.update(visible=False),  # marketplace_content
                            gr.update(visible=False),  # settings_content
                            gr.update(visible=True),   # tool_interfaces
                            gr.update(visible=False),  # tool_details_content
                            gr.update(variant="secondary"),  # tools_btn
                            gr.update(variant="secondary"),  # marketplace_btn
                            gr.update(variant="secondary"),  # settings_btn
                            gr.update(value=restart_message)  # tool_interfaces_html
                        ] + [gr.update(visible=False) for _ in tool_containers]
                
                # For existing tools with proper UI containers
                # Create a list of visibility updates for all tool containers
                updates = []
                
                for i, container in enumerate(tool_containers):
                    # Get the tool_id for this container
                    container_tool_id = None
                    for tid, t in self.tools.items():
                        if hasattr(t, 'ui_container') and t.ui_container == container:
                            container_tool_id = tid
                            break
                    
                    # Set visibility based on whether this is the selected tool
                    if container_tool_id == tool_id:
                        updates.append(gr.update(visible=True))
                    else:
                        updates.append(gr.update(visible=False))
                
                return [
                    gr.update(visible=False),  # tools_content
                    gr.update(visible=False),  # marketplace_content
                    gr.update(visible=False),  # settings_content
                    gr.update(visible=True),   # tool_interfaces
                    gr.update(visible=False),  # tool_details_content
                    gr.update(variant="secondary"),  # tools_btn
                    gr.update(variant="secondary"),  # marketplace_btn
                    gr.update(variant="secondary"),  # settings_btn
                    gr.update(value="")  # tool_interfaces_html
                ] + updates
            
            def show_tool_details(tool_id):
                # Fetch tool details
                tool = self.fetch_tool_details(tool_id)
                
                # Create updates to hide all tool containers
                tool_container_updates = [gr.update(visible=False) for _ in tool_containers]
                
                if not tool:
                    return [
                        gr.update(visible=False),  # tools_content
                        gr.update(visible=True),   # marketplace_content
                        gr.update(visible=False),  # settings_content
                        gr.update(visible=False),  # tool_interfaces
                        gr.update(visible=False),  # tool_details_content
                        gr.update(variant="secondary"),  # tools_btn
                        gr.update(variant="primary"),    # marketplace_btn
                        gr.update(variant="secondary"),  # settings_btn
                        None,  # current_tool_details_state
                        "",    # tool_details_html
                        gr.update(visible=False),  # installation_result_container
                        gr.update(visible=False),   # confirmation_dialog
                        gr.update(value="")  # tool_interfaces_html
                    ] + tool_container_updates
                
                # Create features HTML
                features_html = "".join([
                    f'<div class="tool-details-feature"><span class="tool-details-feature-icon">✓</span><span class="tool-details-feature-text">{feature}</span></div>'
                    for feature in tool.get('features', [])
                ])
                
                # Create demo video HTML
                demo_video_html = f'<iframe class="tool-details-video" src="{tool.get("demo_video", "https://www.youtube.com/embed/dQw4w9WgXcQ")}" frameborder="0" allowfullscreen></iframe>' if True else ''
                
                # Check if the tool is already installed
                # Use the is_installed flag if available, otherwise check self.tools
                is_installed = tool.get('is_installed', False) or tool_id in self.tools
                
                # Determine which button to show based on installation status
                if is_installed:
                    action_button = f'<button id="remove-tool-btn-inline" class="remove-button" onclick="document.getElementById(\'remove-btn\').click()">Remove Tool</button>'
                else:
                    action_button = f'<button id="add-tool-btn-inline" class="install-button" onclick="document.getElementById(\'install-btn\').click()">Add Tool</button>'
                
                # Create HTML for tool details
                html = f'''
                <div class="tool-details-container">
                    <div class="tool-details">
                        <div class="tool-details-header">
                            <div class="tool-details-title-section">
                                <div class="tool-details-icon">{tool['icon']}</div>
                                <h2 class="tool-details-title">{tool['name']} <span class="tool-details-version">v{tool['version']}</span></h2>
                            </div>
                            <div class="tool-details-action">
                                {action_button}
                            </div>
                        </div>
                        <p class="tool-details-description">{tool['description']}</p>
                        
                        <h3 class="tool-details-section-title">Features</h3>
                        <div class="tool-details-features">
                            {features_html}
                        </div>
                        
                        <h3 class="tool-details-section-title">Video</h3>
                        {demo_video_html}
                    </div>
                </div>
                '''
                
                print(f"Setting current_tool_details_state to: {tool}")
                return [
                    gr.update(visible=False),  # tools_content
                    gr.update(visible=False),  # marketplace_content
                    gr.update(visible=False),  # settings_content
                    gr.update(visible=False),  # tool_interfaces
                    gr.update(visible=True),   # tool_details_content
                    gr.update(variant="secondary"),  # tools_btn
                    gr.update(variant="secondary"),  # marketplace_btn
                    gr.update(variant="secondary"),  # settings_btn
                    tool,  # current_tool_details_state
                    html,  # tool_details_html
                    gr.update(visible=False),  # installation_result_container
                    gr.update(visible=False),   # confirmation_dialog
                    gr.update(value="")  # tool_interfaces_html
                ] + tool_container_updates
            
            def install_selected_tool(tool_details):
                print(f"Installing tool: {tool_details}")
                
                if not tool_details:
                    print("No tool details provided")
                    return [
                        gr.update(visible=True),  # installation_result_container
                        "⚠️ Installation Failed",     # installation_status
                        "No tool selected to install."  # installation_result
                    ]
                
                try:
                    # Install the tool
                    result = self.install_tool(tool_details['id'])
                    
                    if "Error" in result:
                        return [
                            gr.update(visible=True),  # installation_result_container
                            "⚠️ Installation Failed",     # installation_status
                            result                       # installation_result
                        ]
                    else:
                        # If installation was successful, we'll show a success message
                        # The user can click "Close" to see the installation result
                        # and then navigate to the tools page to see the new tool
                        return [
                            gr.update(visible=True),  # installation_result_container
                            "✅ Installation Successful",  # installation_status
                            result                        # installation_result
                        ]
                except Exception as e:
                    print(f"Error installing tool: {e}")
                    return [
                        gr.update(visible=True),  # installation_result_container
                        "⚠️ Installation Failed",     # installation_status
                        f"Error installing tool: {e}"  # installation_result
                    ]

            # Create components after defining the functions
            with gr.Row():
                # Sidebar
                with gr.Column(elem_id="sidebar", scale=1):
                    gr.Markdown("AI TOOLS", elem_classes="title")
                    tools_btn = gr.Button("Tools", elem_classes="nav-button", variant="primary")
                    marketplace_btn = gr.Button("Marketplace", elem_classes="nav-button", variant="secondary")
                    settings_btn = gr.Button("Settings", elem_classes="nav-button", variant="secondary")
                    gr.Markdown(f"version: {self.version}", elem_classes="version-text")
                
                # Main content
                with gr.Column(elem_id="main-content", scale=4):
                    # Define all content containers
                    tools_content = gr.Column(visible=True)
                    marketplace_content = gr.Column(visible=False)
                    settings_content = gr.Column(visible=False)
                    tool_interfaces = gr.Column(visible=False)
                    tool_details_content = gr.Column(visible=False)
                    
                    # Fill tools content
                    with tools_content:
                        gr.Markdown("Tools", elem_classes="page-title")
                        
                        tool_buttons = []
                        tool_ids = []  # Store tool_ids in the same order as tool_buttons
                        
                        # Create HTML for all tools
                        tools_html = ''
                        
                        for tool_id, tool in self.tools.items():
                            # Create HTML for each tool card
                            tools_html += f'''
                            <div class="tool-card" id="tool-card-{tool_id}" onclick="document.getElementById('tool-btn-{tool_id}').click()">
                                <div class="tool-card-img">
                                    {tool.icon}
                                </div>
                                <div class="tool-card-content">
                                    <h3 class="tool-card-title">{tool.name}</h3>
                                    <p class="tool-card-description">{tool.description if hasattr(tool, 'description') else ""}</p>
                                </div>
                            </div>
                            '''
                            
                            # Create hidden buttons for tool selection
                            btn = gr.Button(f"Select {tool.name}", visible=False, elem_id=f"tool-btn-{tool_id}")
                            tool_buttons.append(btn)
                            tool_ids.append(tool_id)
                        
                        # Add "Add New Tool" button
                        tools_html += '''
                        <div class="tool-card add-tool-card" onclick="document.getElementById('add-tool-btn').click()">
                            <div class="add-tool-icon">+</div>
                            <div>Add New Tool from Marketplace</div>
                        </div>
                        '''
                        
                        # Render the HTML inside a div with the tool-grid class
                        tools_html_component = gr.HTML(f'<div class="tool-grid">{tools_html}</div>')
                        
                        # Create hidden add tool button
                        add_tool_btn = gr.Button("Add New Tool", visible=False, elem_id="add-tool-btn")
                    
                    # Fill marketplace content
                    with marketplace_content:
                        gr.Markdown("Marketplace", elem_classes="page-title")
                        marketplace_html = gr.HTML("Loading marketplace tools...")
                        
                        # Create hidden buttons for marketplace tool details with unique IDs
                        tool_buttons_container = gr.Column(visible=False)
                        
                        # Create hidden buttons for marketplace tools
                        marketplace_tool_buttons = []
                        for i, tool in enumerate(self.fetch_marketplace_tools()):
                            tool_btn = gr.Button(f"View {tool['name']}", visible=False, elem_id=f"marketplace-tool-btn-{i}")
                            marketplace_tool_buttons.append((tool['id'], tool_btn))
                        
                        # The click handlers for marketplace tool buttons will be set up after all components are defined
                    
                    # Fill tool details content
                    with tool_details_content:
                        # Installation result section at the top
                        with gr.Column(elem_id="installation-result-container", elem_classes="installation-result-container", visible=False) as installation_result_container:
                            installation_status = gr.Markdown("Ready to install", elem_id="installation-status")
                            installation_result = gr.Markdown("Click the Install Tool button to install the selected tool.", elem_id="installation-result")
                            close_result_btn = gr.Button("Close", elem_id="close-result-btn")
                        
                        # Confirmation dialog for tool removal
                        with gr.Column(elem_id="confirmation-dialog", elem_classes="confirmation-dialog", visible=False) as confirmation_dialog:
                            gr.Markdown("⚠️ Warning: Remove Tool", elem_id="confirmation-title", elem_classes="confirmation-title")
                            gr.Markdown(
                                "Are you sure you want to remove this tool? This action cannot be undone. "
                                "All data created by this tool will be permanently deleted.", 
                                elem_id="confirmation-message", 
                                elem_classes="confirmation-message"
                            )
                            with gr.Row(elem_classes="confirmation-buttons"):
                                cancel_btn = gr.Button("Cancel", elem_classes="cancel-button")
                                confirm_btn = gr.Button("Yes, Remove Tool", elem_classes="confirm-button")
                            
                        with gr.Row():
                            with gr.Column(scale=1):
                                back_btn = gr.Button("← Back to Marketplace", elem_classes="back-button")
                            with gr.Column(scale=3):
                                gr.Markdown("", elem_classes="page-title")
                        
                        # Tool details content
                        tool_details_html = gr.HTML("")
                        
                        # Hidden install button (will be triggered by the inline button)
                        install_btn = gr.Button("Add Tool", elem_classes="install-button", elem_id="install-btn", variant="primary", visible=False)
                        
                        # Hidden remove button (will be triggered by the inline button)
                        remove_btn = gr.Button("Remove Tool", elem_classes="remove-button", elem_id="remove-btn", variant="primary", visible=False)
                        
                        # Add a direct event handler to the install button
                        def debug_install_click():
                            print("Install button clicked directly!")
                            return [gr.update(visible=True), gr.update(value="Install button clicked!")]
                        
                        # Add a direct event handler to the remove button to show confirmation dialog
                        def show_confirmation_dialog():
                            print("Remove button clicked - showing confirmation dialog")
                            return gr.update(visible=True)
                        
                        # Function to handle tool removal confirmation
                        def remove_selected_tool(tool_details):
                            print(f"Removing tool: {tool_details}")
                            
                            if not tool_details:
                                print("No tool details provided")
                                return [
                                    gr.update(visible=False),  # confirmation_dialog
                                    gr.update(visible=True),   # installation_result_container
                                    "⚠️ Removal Failed",       # installation_status
                                    "No tool selected to remove."  # installation_result
                                ]
                            
                            try:
                                # Remove the tool
                                result = self.remove_tool(tool_details['id'])
                                
                                if "Error" in result:
                                    return [
                                        gr.update(visible=False),  # confirmation_dialog
                                        gr.update(visible=True),   # installation_result_container
                                        "⚠️ Removal Failed",       # installation_status
                                        result                     # installation_result
                                    ]
                                else:
                                    # After successful removal, show success message
                                    # The user will need to click "Back to Marketplace" manually
                                    # This avoids issues with dynamic UI updates
                                    return [
                                        gr.update(visible=False),  # confirmation_dialog
                                        gr.update(visible=True),   # installation_result_container
                                        "✅ Removal Successful",   # installation_status
                                        f"{result} - Click 'Back to Marketplace' to return. You may need to restart the application to see all changes."  # installation_result
                                    ]
                            except Exception as e:
                                print(f"Error removing tool: {e}")
                                return [
                                    gr.update(visible=False),  # confirmation_dialog
                                    gr.update(visible=True),   # installation_result_container
                                    "⚠️ Removal Failed",       # installation_status
                                    f"Error removing tool: {e}"  # installation_result
                                ]
                        
                        # Function to cancel removal
                        def cancel_removal():
                            return gr.update(visible=False)
                        
                        debug_output = gr.Textbox(label="Debug Output", visible=False)
                        
                        # Set up event handlers for buttons
                        install_btn.click(
                            fn=install_selected_tool,
                            inputs=[current_tool_details_state],
                            outputs=[installation_result_container, installation_status, installation_result]
                        )
                        remove_btn.click(fn=show_confirmation_dialog, outputs=confirmation_dialog)
                        
                        # Set up confirmation dialog buttons
                        cancel_btn.click(fn=cancel_removal, outputs=confirmation_dialog)
                        confirm_btn.click(
                            fn=remove_selected_tool,
                            inputs=[current_tool_details_state],
                            outputs=[confirmation_dialog, installation_result_container, installation_status, installation_result]
                        )
                    
                    # Fill settings content
                    with settings_content:
                        gr.Markdown("Settings", elem_classes="page-title")
                        gr.Markdown("Settings options will appear here...")
                    
                    # Fill tool interfaces
                    with tool_interfaces:
                        # Add an HTML component to display messages for newly installed tools
                        tool_interfaces_html = gr.HTML("", elem_id="tool-interfaces-html")
                        
                        for tool_id, tool in self.tools.items():
                            with gr.Column(visible=False) as tool_container:
                                tool_ui = tool.ui_class()
                                tool_ui.create_ui()
                            # Store the UI container in the tool object for later reference
                            tool.ui_container = tool_container
            
            # Set up event handlers after all components are defined
            # Set up tool button events
            
            # Collect all tool containers for outputs
            tool_containers = []
            for tool_id, tool in self.tools.items():
                if hasattr(tool, 'ui_container'):
                    tool_containers.append(tool.ui_container)
            
            # Set up click handlers for marketplace tool buttons
            for i, (tool_id, tool_btn) in enumerate(marketplace_tool_buttons):
                # We need to create a separate function for each button to avoid lambda closure issues
                def make_handler(tid):
                    return lambda: show_tool_details(tid)
                
                handler = make_handler(tool_id)
                tool_btn.click(
                    fn=handler,
                    outputs=[
                        tools_content, marketplace_content, settings_content, tool_interfaces, 
                        tool_details_content, tools_btn, marketplace_btn, settings_btn,
                        current_tool_details_state, tool_details_html, installation_result_container,
                        confirmation_dialog, tool_interfaces_html
                    ] + tool_containers
                )
            
            for i, btn in enumerate(tool_buttons):
                if isinstance(btn, gr.Button):  # Check if it's a button from the tools grid
                    tool_id = tool_ids[i]  # Get the corresponding tool_id
                    
                    # We need to create a separate function for each button to avoid lambda closure issues
                    def make_handler(tid):
                        return lambda: show_tool(tid)
                    
                    handler = make_handler(tool_id)
                    btn.click(
                        fn=handler,
                        outputs=[tools_content, marketplace_content, settings_content, tool_interfaces, 
                                tool_details_content, tools_btn, marketplace_btn, settings_btn,
                                tool_interfaces_html] + tool_containers
                    )
            
            # Set up navigation events
            tools_btn.click(
                fn=show_tools,
                outputs=[tools_content, marketplace_content, settings_content, tool_interfaces, 
                        tool_details_content, tools_btn, marketplace_btn, settings_btn,
                        tools_html_component, tool_interfaces_html] + tool_containers
            )
            
            marketplace_btn.click(
                fn=show_marketplace,
                outputs=[tools_content, marketplace_content, settings_content, tool_interfaces, 
                        tool_details_content, tools_btn, marketplace_btn, settings_btn,
                        marketplace_tools_state, marketplace_html, installation_result_container,
                        confirmation_dialog, tool_interfaces_html] + tool_containers
            )
            
            settings_btn.click(
                fn=show_settings,
                outputs=[tools_content, marketplace_content, settings_content, tool_interfaces, 
                        tool_details_content, tools_btn, marketplace_btn, settings_btn,
                        tool_interfaces_html] + tool_containers
            )
            
            # Set up add tool button to navigate to marketplace
            add_tool_btn.click(
                fn=show_marketplace,
                outputs=[tools_content, marketplace_content, settings_content, tool_interfaces, 
                        tool_details_content, tools_btn, marketplace_btn, settings_btn,
                        marketplace_tools_state, marketplace_html, installation_result_container,
                        confirmation_dialog, tool_interfaces_html] + tool_containers
            )
            
            # Set up event handlers for tool details
            back_btn.click(
                fn=show_marketplace,
                outputs=[
                    tools_content, marketplace_content, settings_content, tool_interfaces, 
                    tool_details_content, tools_btn, marketplace_btn, settings_btn,
                    marketplace_tools_state, marketplace_html, installation_result_container,
                    confirmation_dialog
                ] + tool_containers
            )
            
            # Define a function to handle closing the installation result and navigating to tools
            def close_result_and_show_tools():
                # First hide the installation result container
                installation_result_update = gr.update(visible=False)
                
                # Then get the updates from show_tools
                tools_updates = show_tools()
                
                # Combine the updates
                return [installation_result_update] + tools_updates
            
            # Set up close button for installation result
            close_result_btn.click(
                fn=close_result_and_show_tools,
                outputs=[installation_result_container, 
                         tools_content, marketplace_content, settings_content, tool_interfaces, 
                         tool_details_content, tools_btn, marketplace_btn, settings_btn,
                         tools_html_component, tool_interfaces_html] + tool_containers
            )

        return app

if __name__ == "__main__":
    ui = MainUI()
    demo = ui.create_ui()
    demo.queue()  # Add queue for better handling of multiple requests
    demo.title = "AI Tools Platform"  # Add a title
    demo.launch(
        debug=True,
        share=True,
        server_name="0.0.0.0",
        server_port=7860
    )