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
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
// ============================================
// Settings management
// ============================================

// Migrate old settings format (v1) to new format (v2)
function migrateSettings(oldSettings) {
    // Already migrated or new format
    if (oldSettings.settingsVersion >= 2) {
        return oldSettings;
    }

    console.log('Migrating settings from v1 to v2...');

    const newSettings = {
        providers: {},
        models: {},
        agents: {
            command: '',
            agent: '',
            code: '',
            research: '',
            chat: ''
        },
        e2bKey: oldSettings.e2bKey || '',
        serperKey: oldSettings.serperKey || '',
        hfToken: oldSettings.hfToken || '',
        imageGenModel: oldSettings.imageGenModel || '',
        imageEditModel: oldSettings.imageEditModel || '',
        researchSubAgentModel: oldSettings.researchSubAgentModel || '',
        researchParallelWorkers: oldSettings.researchParallelWorkers || null,
        researchMaxWebsites: oldSettings.researchMaxWebsites || null,
        themeColor: oldSettings.themeColor || 'forest',
        settingsVersion: 2
    };

    // Create a default provider from old endpoint/token if they exist
    if (oldSettings.endpoint) {
        const providerId = 'provider_default';
        newSettings.providers[providerId] = {
            name: 'Default',
            endpoint: oldSettings.endpoint,
            token: oldSettings.token || ''
        };

        // Create a default model if old model exists
        if (oldSettings.model) {
            const modelId = 'model_default';
            newSettings.models[modelId] = {
                name: oldSettings.model,
                providerId: providerId,
                modelId: oldSettings.model
            };

            // Set as default for all agents
            newSettings.agents.command = modelId;
            newSettings.agents.agent = modelId;
            newSettings.agents.code = modelId;
            newSettings.agents.research = modelId;
            newSettings.agents.chat = modelId;
        }

        // Migrate agent-specific models if they existed
        const oldModels = oldSettings.models || {};
        const agentTypes = Object.keys(AGENT_REGISTRY).filter(k => AGENT_REGISTRY[k].hasCounter);
        agentTypes.forEach(type => {
            if (oldModels[type]) {
                const specificModelId = `model_${type}`;
                newSettings.models[specificModelId] = {
                    name: `${type.charAt(0).toUpperCase() + type.slice(1)} - ${oldModels[type]}`,
                    providerId: providerId,
                    modelId: oldModels[type]
                };
                newSettings.agents[type] = specificModelId;
            }
        });
    }

    console.log('Settings migrated:', newSettings);
    return newSettings;
}

async function loadSettings() {
    let loadedSettings = null;

    // Try to load from backend API (file-based) first
    try {
        const response = await apiFetch('/api/settings');
        if (response.ok) {
            loadedSettings = await response.json();
            console.log('Settings loaded from file:', loadedSettings);
        }
    } catch (e) {
        console.log('Could not load settings from backend, falling back to localStorage');
    }

    // Fallback to localStorage if backend is unavailable
    if (!loadedSettings) {
        const savedSettings = localStorage.getItem('agentui_settings') || localStorage.getItem('productive_settings');
        console.log('Loading settings from localStorage:', savedSettings ? 'found' : 'not found');
        if (savedSettings) {
            try {
                loadedSettings = JSON.parse(savedSettings);
                console.log('Settings loaded from localStorage:', loadedSettings);
            } catch (e) {
                console.error('Failed to parse settings:', e);
            }
        }
    }

    if (loadedSettings) {
        // Migrate old "notebooks" key to "agents"
        if (loadedSettings.notebooks && !loadedSettings.agents) {
            loadedSettings.agents = loadedSettings.notebooks;
            delete loadedSettings.notebooks;
        }
        // Migrate if needed
        if (!loadedSettings.settingsVersion || loadedSettings.settingsVersion < 2) {
            loadedSettings = migrateSettings(loadedSettings);
            // Save migrated settings
            try {
                await apiFetch('/api/settings', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(loadedSettings)
                });
                console.log('Migrated settings saved to file');
            } catch (e) {
                console.log('Could not save migrated settings to file');
            }
        }
        settings = { ...settings, ...loadedSettings };
    } else {
        console.log('Using default settings:', settings);
    }
}

// Generate unique ID for providers/models
function generateId(prefix) {
    return `${prefix}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}

// Render providers list in settings
function renderProvidersList() {
    const container = document.getElementById('providers-list');
    if (!container) return;

    const providers = settings.providers || {};
    let html = '';

    Object.entries(providers).forEach(([id, provider]) => {
        html += `
            <div class="provider-item" data-provider-id="${id}">
                <div class="provider-info">
                    <span class="provider-name">${escapeHtml(provider.name)}</span>
                    <span class="provider-endpoint">${escapeHtml(provider.endpoint)}</span>
                </div>
                <div class="provider-actions">
                    <button class="provider-edit-btn" onclick="editProvider('${id}')" title="Edit">✎</button>
                    <button class="provider-delete-btn" onclick="deleteProvider('${id}')" title="Delete">×</button>
                </div>
            </div>
        `;
    });

    if (Object.keys(providers).length === 0) {
        html = '<div class="empty-list">No providers configured. Add one to get started.</div>';
    }

    container.innerHTML = html;
}

// Render models list in settings
function renderModelsList() {
    const container = document.getElementById('models-list');
    if (!container) return;

    const models = settings.models || {};
    const providers = settings.providers || {};
    let html = '';

    Object.entries(models).forEach(([id, model]) => {
        const provider = providers[model.providerId];
        const providerName = provider ? provider.name : 'Unknown';
        html += `
            <div class="model-item" data-model-id="${id}">
                <div class="model-info">
                    <span class="model-name">${escapeHtml(model.name)}</span>
                    <span class="model-details">${escapeHtml(model.modelId)} @ ${escapeHtml(providerName)}</span>
                </div>
                <div class="model-actions">
                    <button class="model-edit-btn" onclick="editModel('${id}')" title="Edit">✎</button>
                    <button class="model-delete-btn" onclick="deleteModel('${id}')" title="Delete">×</button>
                </div>
            </div>
        `;
    });

    if (Object.keys(models).length === 0) {
        html = '<div class="empty-list">No models configured. Add a provider first, then add models.</div>';
    }

    container.innerHTML = html;
}

// Populate model dropdowns for agent selection
function populateModelDropdowns() {
    const models = settings.models || {};
    const agents = settings.agents || {};

    // Build dropdown IDs from registry + special dropdowns
    const dropdownIds = [
        ...Object.keys(AGENT_REGISTRY).map(t => `setting-agent-${t}`),
        'setting-research-sub-agent-model',
        'setting-image-gen-model',
        'setting-image-edit-model'
    ];

    dropdownIds.forEach(dropdownId => {
        const dropdown = document.getElementById(dropdownId);
        if (!dropdown) return;

        // Preserve current selection
        const currentValue = dropdown.value;

        // Clear and rebuild options
        dropdown.innerHTML = '<option value="">-- Select Model --</option>';

        Object.entries(models).forEach(([id, model]) => {
            const option = document.createElement('option');
            option.value = id;
            option.textContent = `${model.name} (${model.modelId})`;
            dropdown.appendChild(option);
        });

        // Restore selection
        if (currentValue && models[currentValue]) {
            dropdown.value = currentValue;
        }
    });

    // Set values from settings (driven by registry)
    for (const type of Object.keys(AGENT_REGISTRY)) {
        const dropdown = document.getElementById(`setting-agent-${type}`);
        if (dropdown) dropdown.value = agents[type] || '';
    }
    const subAgentDropdown = document.getElementById('setting-research-sub-agent-model');
    if (subAgentDropdown) subAgentDropdown.value = settings.researchSubAgentModel || '';
    const imageGenDropdown = document.getElementById('setting-image-gen-model');
    if (imageGenDropdown) imageGenDropdown.value = settings.imageGenModel || '';
    const imageEditDropdown = document.getElementById('setting-image-edit-model');
    if (imageEditDropdown) imageEditDropdown.value = settings.imageEditModel || '';
}

// Show add/edit provider dialog
function showProviderDialog(providerId = null) {
    const isEdit = !!providerId;
    const provider = isEdit ? settings.providers[providerId] : { name: '', endpoint: '', token: '' };

    const dialog = document.getElementById('provider-dialog');
    const title = document.getElementById('provider-dialog-title');
    const nameInput = document.getElementById('provider-name');
    const endpointInput = document.getElementById('provider-endpoint');
    const tokenInput = document.getElementById('provider-token');

    title.textContent = isEdit ? 'Edit Provider' : 'Add Provider';
    nameInput.value = provider.name;
    endpointInput.value = provider.endpoint;
    tokenInput.value = provider.token;

    dialog.dataset.providerId = providerId || '';
    dialog.classList.add('active');
}

// Hide provider dialog
function hideProviderDialog() {
    const dialog = document.getElementById('provider-dialog');
    dialog.classList.remove('active');
}

// Save provider from dialog
function saveProviderFromDialog() {
    const dialog = document.getElementById('provider-dialog');
    const providerId = dialog.dataset.providerId || generateId('provider');
    const name = document.getElementById('provider-name').value.trim();
    const endpoint = document.getElementById('provider-endpoint').value.trim();
    const token = document.getElementById('provider-token').value.trim();

    if (!name || !endpoint) {
        alert('Provider name and endpoint are required');
        return;
    }

    settings.providers[providerId] = { name, endpoint, token };
    hideProviderDialog();
    renderProvidersList();
    populateModelDropdowns();
}

// Edit provider
function editProvider(providerId) {
    showProviderDialog(providerId);
}

// Delete provider
function deleteProvider(providerId) {
    // Check if any models use this provider
    const modelsUsingProvider = Object.entries(settings.models || {})
        .filter(([_, model]) => model.providerId === providerId);

    if (modelsUsingProvider.length > 0) {
        alert(`Cannot delete provider. ${modelsUsingProvider.length} model(s) are using it.`);
        return;
    }

    if (confirm('Delete this provider?')) {
        delete settings.providers[providerId];
        renderProvidersList();
    }
}

// Show add/edit model dialog
function showModelDialog(modelId = null) {
    const isEdit = !!modelId;
    const model = isEdit ? settings.models[modelId] : { name: '', providerId: '', modelId: '', extraParams: null, multimodal: false };

    const dialog = document.getElementById('model-dialog');
    const title = document.getElementById('model-dialog-title');
    const nameInput = document.getElementById('model-name');
    const providerSelect = document.getElementById('model-provider');
    const modelIdInput = document.getElementById('model-model-id');
    const extraParamsInput = document.getElementById('model-extra-params');
    const multimodalCheckbox = document.getElementById('model-multimodal');

    title.textContent = isEdit ? 'Edit Model' : 'Add Model';
    nameInput.value = model.name;
    modelIdInput.value = model.modelId;
    extraParamsInput.value = model.extraParams ? JSON.stringify(model.extraParams, null, 2) : '';
    multimodalCheckbox.checked = !!model.multimodal;

    // Populate provider dropdown
    providerSelect.innerHTML = '<option value="">-- Select Provider --</option>';
    Object.entries(settings.providers || {}).forEach(([id, provider]) => {
        const option = document.createElement('option');
        option.value = id;
        option.textContent = provider.name;
        if (id === model.providerId) option.selected = true;
        providerSelect.appendChild(option);
    });

    dialog.dataset.modelId = modelId || '';
    dialog.classList.add('active');
}

// Hide model dialog
function hideModelDialog() {
    const dialog = document.getElementById('model-dialog');
    dialog.classList.remove('active');
}

// Save model from dialog
function saveModelFromDialog() {
    const dialog = document.getElementById('model-dialog');
    const modelId = dialog.dataset.modelId || generateId('model');
    const name = document.getElementById('model-name').value.trim();
    const providerId = document.getElementById('model-provider').value;
    const apiModelId = document.getElementById('model-model-id').value.trim();
    const extraParamsStr = document.getElementById('model-extra-params').value.trim();

    if (!name || !providerId || !apiModelId) {
        alert('Name, provider, and model ID are required');
        return;
    }

    // Parse extra params if provided
    let extraParams = null;
    if (extraParamsStr) {
        try {
            extraParams = JSON.parse(extraParamsStr);
        } catch (e) {
            alert('Invalid JSON in extra parameters: ' + e.message);
            return;
        }
    }

    const multimodal = document.getElementById('model-multimodal').checked;
    settings.models[modelId] = { name, providerId, modelId: apiModelId, extraParams, multimodal };
    hideModelDialog();
    renderModelsList();
    populateModelDropdowns();
}

// Edit model
function editModel(modelId) {
    showModelDialog(modelId);
}

// Delete model
function deleteModel(modelId) {
    // Check if any agents use this model
    const agentsUsingModel = Object.entries(settings.agents || {})
        .filter(([_, mid]) => mid === modelId);

    if (agentsUsingModel.length > 0) {
        const warning = `This model is used by: ${agentsUsingModel.map(([t]) => t).join(', ')}. Delete anyway?`;
        if (!confirm(warning)) return;

        // Clear the agent assignments
        agentsUsingModel.forEach(([type]) => {
            settings.agents[type] = '';
        });
    } else if (!confirm('Delete this model?')) {
        return;
    }

    delete settings.models[modelId];
    renderModelsList();
    populateModelDropdowns();
}

function openSettings() {
    // Show settings file path
    const pathEl = document.getElementById('settingsPath');
    if (pathEl) pathEl.textContent = settings._settingsPath || '';

    // Render providers and models lists
    renderProvidersList();
    renderModelsList();
    populateModelDropdowns();

    // Populate service keys
    document.getElementById('setting-e2b-key').value = settings.e2bKey || '';
    document.getElementById('setting-serper-key').value = settings.serperKey || '';
    document.getElementById('setting-hf-token').value = settings.hfToken || '';

    // Populate research settings
    document.getElementById('setting-research-parallel-workers').value = settings.researchParallelWorkers || '';
    document.getElementById('setting-research-max-websites').value = settings.researchMaxWebsites || '';

    // Set theme color
    const themeColor = settings.themeColor || 'forest';
    document.getElementById('setting-theme-color').value = themeColor;

    // Update selected theme in picker
    const themePicker = document.getElementById('theme-color-picker');
    if (themePicker) {
        themePicker.querySelectorAll('.theme-option').forEach(opt => {
            opt.classList.remove('selected');
            if (opt.dataset.theme === themeColor) {
                opt.classList.add('selected');
            }
        });
    }

    // Clear any status message
    const status = document.getElementById('settingsStatus');
    status.className = 'settings-status';
    status.textContent = '';
}

async function saveSettings() {
    // Get agent model selections from dropdowns (driven by registry)
    const agentModels = {};
    for (const type of Object.keys(AGENT_REGISTRY)) {
        agentModels[type] = document.getElementById(`setting-agent-${type}`)?.value || '';
    }
    const researchSubAgentModel = document.getElementById('setting-research-sub-agent-model')?.value || '';

    // Get other settings
    const e2bKey = document.getElementById('setting-e2b-key').value.trim();
    const serperKey = document.getElementById('setting-serper-key').value.trim();
    const hfToken = document.getElementById('setting-hf-token').value.trim();
    const imageGenModel = document.getElementById('setting-image-gen-model')?.value || '';
    const imageEditModel = document.getElementById('setting-image-edit-model')?.value || '';
    const researchParallelWorkers = document.getElementById('setting-research-parallel-workers').value.trim();
    const researchMaxWebsites = document.getElementById('setting-research-max-websites').value.trim();
    const themeColor = document.getElementById('setting-theme-color').value || 'forest';

    // Validate: at least one provider and one model should exist
    if (Object.keys(settings.providers || {}).length === 0) {
        showSettingsStatus('Please add at least one provider', 'error');
        return;
    }

    if (Object.keys(settings.models || {}).length === 0) {
        showSettingsStatus('Please add at least one model', 'error');
        return;
    }

    // Update settings
    settings.agents = agentModels;
    settings.e2bKey = e2bKey;
    settings.serperKey = serperKey;
    settings.hfToken = hfToken;
    settings.imageGenModel = imageGenModel;
    settings.imageEditModel = imageEditModel;
    settings.researchSubAgentModel = researchSubAgentModel;
    settings.researchParallelWorkers = researchParallelWorkers ? parseInt(researchParallelWorkers) : null;
    settings.researchMaxWebsites = researchMaxWebsites ? parseInt(researchMaxWebsites) : null;
    settings.themeColor = themeColor;
    settings.settingsVersion = 2;

    // Save to backend API (file-based) first
    try {
        const response = await apiFetch('/api/settings', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(settings)
        });
        if (response.ok) {
            console.log('Settings saved to file:', settings);
        } else {
            console.error('Failed to save settings to file, falling back to localStorage');
            localStorage.setItem('agentui_settings', JSON.stringify(settings));
        }
    } catch (e) {
        console.error('Could not save settings to backend, falling back to localStorage:', e);
        localStorage.setItem('agentui_settings', JSON.stringify(settings));
    }

    // Apply theme
    applyTheme(themeColor);

    // Show success message
    showSettingsStatus('Settings saved successfully', 'success');

    // Close settings panel and go back to command center after a short delay
    setTimeout(() => {
        const settingsPanel = document.getElementById('settingsPanel');
        const settingsBtn = document.getElementById('settingsBtn');
        const appContainer = document.querySelector('.app-container');
        if (settingsPanel) settingsPanel.classList.remove('active');
        if (settingsBtn) settingsBtn.classList.remove('active');
        if (appContainer) appContainer.classList.remove('panel-open');
    }, 1000);
}

function showSettingsStatus(message, type) {
    const status = document.getElementById('settingsStatus');
    status.textContent = message;
    status.className = `settings-status ${type}`;
}

// Theme colors mapping
// Default light surface colors shared by all light themes
const lightSurface = {
    bgPrimary: '#ffffff',
    bgSecondary: '#f5f5f5',
    bgTertiary: '#fafafa',
    bgInput: '#ffffff',
    bgHover: '#f0f0f0',
    bgCard: '#ffffff',
    textPrimary: '#1a1a1a',
    textSecondary: '#666666',
    textMuted: '#999999',
    borderPrimary: '#e0e0e0',
    borderSubtle: '#f0f0f0'
};

const themeColors = {
    forest: {
        border: '#1b5e20', bg: '#e8f5e9', hoverBg: '#c8e6c9',
        accent: '#1b5e20', accentRgb: '27, 94, 32',
        ...lightSurface
    },
    sapphire: {
        border: '#0d47a1', bg: '#e3f2fd', hoverBg: '#bbdefb',
        accent: '#0d47a1', accentRgb: '13, 71, 161',
        ...lightSurface
    },
    ocean: {
        border: '#00796b', bg: '#e0f2f1', hoverBg: '#b2dfdb',
        accent: '#004d40', accentRgb: '0, 77, 64',
        ...lightSurface
    },
    midnight: {
        border: '#283593', bg: '#e8eaf6', hoverBg: '#c5cae9',
        accent: '#1a237e', accentRgb: '26, 35, 126',
        ...lightSurface
    },
    steel: {
        border: '#455a64', bg: '#eceff1', hoverBg: '#cfd8dc',
        accent: '#263238', accentRgb: '38, 50, 56',
        ...lightSurface
    },
    depths: {
        border: '#01579b', bg: '#e3f2fd', hoverBg: '#bbdefb',
        accent: '#01579b', accentRgb: '1, 87, 155',
        ...lightSurface
    },
    ember: {
        border: '#b71c1c', bg: '#fbe9e7', hoverBg: '#ffccbc',
        accent: '#b71c1c', accentRgb: '183, 28, 28',
        ...lightSurface
    },
    noir: {
        border: '#888888', bg: '#1a1a1a', hoverBg: '#2a2a2a',
        accent: '#999999', accentRgb: '153, 153, 153',
        bgPrimary: '#111111',
        bgSecondary: '#1a1a1a',
        bgTertiary: '#0d0d0d',
        bgInput: '#0d0d0d',
        bgHover: '#2a2a2a',
        bgCard: '#1a1a1a',
        textPrimary: '#e0e0e0',
        textSecondary: '#999999',
        textMuted: '#666666',
        borderPrimary: '#333333',
        borderSubtle: '#222222'
    },
    eclipse: {
        border: '#5c9eff', bg: '#0d1520', hoverBg: '#162030',
        accent: '#5c9eff', accentRgb: '92, 158, 255',
        bgPrimary: '#0b1118',
        bgSecondary: '#111a25',
        bgTertiary: '#080e14',
        bgInput: '#080e14',
        bgHover: '#1a2840',
        bgCard: '#111a25',
        textPrimary: '#d0d8e8',
        textSecondary: '#7088a8',
        textMuted: '#4a6080',
        borderPrimary: '#1e2e45',
        borderSubtle: '#151f30'
    },
    terminal: {
        border: '#00cc00', bg: '#0a1a0a', hoverBg: '#0d260d',
        accent: '#00cc00', accentRgb: '0, 204, 0',
        bgPrimary: '#0a0a0a',
        bgSecondary: '#0d1a0d',
        bgTertiary: '#050505',
        bgInput: '#050505',
        bgHover: '#1a3a1a',
        bgCard: '#0d1a0d',
        textPrimary: '#00cc00',
        textSecondary: '#009900',
        textMuted: '#007700',
        borderPrimary: '#1a3a1a',
        borderSubtle: '#0d1a0d'
    }
};

function applyTheme(themeName) {
    const theme = themeColors[themeName] || themeColors.forest;
    const root = document.documentElement;

    // Accent colors
    root.style.setProperty('--theme-border', theme.border);
    root.style.setProperty('--theme-bg', theme.bg);
    root.style.setProperty('--theme-hover-bg', theme.hoverBg);
    root.style.setProperty('--theme-accent', theme.accent);
    root.style.setProperty('--theme-accent-rgb', theme.accentRgb);

    // Surface colors
    root.style.setProperty('--bg-primary', theme.bgPrimary);
    root.style.setProperty('--bg-secondary', theme.bgSecondary);
    root.style.setProperty('--bg-tertiary', theme.bgTertiary);
    root.style.setProperty('--bg-input', theme.bgInput);
    root.style.setProperty('--bg-hover', theme.bgHover);
    root.style.setProperty('--bg-card', theme.bgCard);
    root.style.setProperty('--text-primary', theme.textPrimary);
    root.style.setProperty('--text-secondary', theme.textSecondary);
    root.style.setProperty('--text-muted', theme.textMuted);
    root.style.setProperty('--border-primary', theme.borderPrimary);
    root.style.setProperty('--border-subtle', theme.borderSubtle);

    // Data attribute for any remaining theme-specific overrides
    document.body.setAttribute('data-theme', themeName);
}

// Export settings for use in API calls
function getSettings() {
    return settings;
}

// Resolve model configuration for an agent type
// Returns { endpoint, token, model, extraParams } or null if not configured
function resolveModelConfig(agentType) {
    const modelId = settings.agents?.[agentType];
    if (!modelId) return null;

    const model = settings.models?.[modelId];
    if (!model) return null;

    const provider = settings.providers?.[model.providerId];
    if (!provider) return null;

    return {
        endpoint: provider.endpoint,
        token: provider.token,
        model: model.modelId,
        extraParams: model.extraParams || null,
        multimodal: !!model.multimodal
    };
}

// Get first available model config as fallback
function getDefaultModelConfig() {
    const modelIds = Object.keys(settings.models || {});
    if (modelIds.length === 0) return null;

    const modelId = modelIds[0];
    const model = settings.models[modelId];
    const provider = settings.providers?.[model.providerId];
    if (!provider) return null;

    return {
        endpoint: provider.endpoint,
        token: provider.token,
        model: model.modelId,
        extraParams: model.extraParams || null,
        multimodal: !!model.multimodal
    };
}

// Build frontend context for API requests
function getFrontendContext() {
    const currentThemeName = settings.themeColor || 'forest';
    const theme = themeColors[currentThemeName];

    return {
        theme: theme ? {
            name: currentThemeName,
            accent: theme.accent,
            bg: theme.bg,
            border: theme.border,
            bgPrimary: theme.bgPrimary,
            bgSecondary: theme.bgSecondary,
            textPrimary: theme.textPrimary,
            textSecondary: theme.textSecondary
        } : null,
        open_agents: getOpenAgentTypes()
    };
}

// Get list of open agent types
function getOpenAgentTypes() {
    const tabs = document.querySelectorAll('.tab[data-tab-id]');
    const types = [];
    tabs.forEach(tab => {
        const tabId = tab.dataset.tabId;
        if (tabId === '0') {
            types.push('command');
        } else {
            const content = document.querySelector(`[data-content-id="${tabId}"]`);
            if (content) {
                const chatContainer = content.querySelector('.chat-container');
                if (chatContainer && chatContainer.dataset.agentType) {
                    types.push(chatContainer.dataset.agentType);
                }
            }
        }
    });
    return types;
}

// Sandbox management for code agents
async function startSandbox(tabId) {
    const currentSettings = getSettings();
    const backendEndpoint = '/api';

    if (!currentSettings.e2bKey) {
        console.log('No E2B key configured, skipping sandbox start');
        return;
    }

    // Add a status message to the agent
    const uniqueId = `code-${tabId}`;
    const chatContainer = document.getElementById(`messages-${uniqueId}`);
    if (chatContainer) {
        const statusMsg = document.createElement('div');
        statusMsg.className = 'system-message';
        statusMsg.innerHTML = '<em>⚙️ Starting sandbox...</em>';
        chatContainer.appendChild(statusMsg);
    }

    try {
        const response = await apiFetch(`${backendEndpoint}/sandbox/start`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                session_id: tabId.toString(),
                e2b_key: currentSettings.e2bKey
            })
        });

        const result = await response.json();

        // Update status message
        if (chatContainer) {
            const statusMsg = chatContainer.querySelector('.system-message');
            if (statusMsg) {
                if (result.success) {
                    // Sandbox is ready - hide the message
                    statusMsg.remove();
                } else {
                    statusMsg.innerHTML = `<em>⚠ Sandbox error: ${result.error}</em>`;
                    statusMsg.style.color = '#c62828';
                }
            }
        }
    } catch (error) {
        console.error('Failed to start sandbox:', error);
        if (chatContainer) {
            const statusMsg = chatContainer.querySelector('.system-message');
            if (statusMsg) {
                statusMsg.innerHTML = `<em>⚠ Failed to start sandbox: ${error.message}</em>`;
                statusMsg.style.color = '#c62828';
            }
        }
    }
}

async function stopSandbox(tabId) {
    const backendEndpoint = '/api';

    try {
        await apiFetch(`${backendEndpoint}/sandbox/stop`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                session_id: tabId.toString()
            })
        });
    } catch (error) {
        console.error('Failed to stop sandbox:', error);
    }
}

// Image modal for click-to-zoom
function openImageModal(src) {
    // Create modal if it doesn't exist
    let modal = document.getElementById('imageModal');
    if (!modal) {
        modal = document.createElement('div');
        modal.id = 'imageModal';
        modal.style.cssText = `
            display: none;
            position: fixed;
            z-index: 10000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.9);
            cursor: pointer;
        `;
        modal.onclick = function() {
            modal.style.display = 'none';
        };

        const img = document.createElement('img');
        img.id = 'imageModalContent';
        img.style.cssText = `
            margin: auto;
            display: block;
            max-width: 95%;
            max-height: 95%;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        `;
        modal.appendChild(img);
        document.body.appendChild(modal);
    }

    // Show modal with image
    const modalImg = document.getElementById('imageModalContent');
    modalImg.src = src;
    modal.style.display = 'block';
}

// ============= DEBUG PANEL =============

const debugPanel = document.getElementById('debugPanel');
const debugBtn = document.getElementById('debugBtn');
const debugClose = document.getElementById('debugClose');
const debugContent = document.getElementById('debugContent');

// Toggle debug panel
if (debugBtn) {
    debugBtn.addEventListener('click', () => {
        const isOpening = !debugPanel.classList.contains('active');

        // Close all panels first, then toggle debug
        closeAllPanels();

        if (isOpening) {
            debugPanel.classList.add('active');
            debugBtn.classList.add('active');
            appContainer.classList.add('panel-open');
            loadDebugMessages();
        }
    });
}

// Close debug panel
if (debugClose) {
    debugClose.addEventListener('click', () => {
        debugPanel.classList.remove('active');
        debugBtn.classList.remove('active');
        appContainer.classList.remove('panel-open');
    });
}


// Load debug messages from backend
function formatDebugJson(obj) {
    /**
     * Format an object as HTML-escaped JSON, replacing base64 image data
     * with clickable placeholders that show a thumbnail on hover.
     */
    // Collect base64 images and replace with placeholders before escaping
    const images = [];
    const json = JSON.stringify(obj, null, 2);
    const placeholder = json.replace(
        /"(data:image\/[^;]+;base64,)([A-Za-z0-9+/=\n]{200,})"/g,
        (match, prefix, b64) => {
            const idx = images.length;
            const sizeKB = (b64.length * 0.75 / 1024).toFixed(1);
            images.push(prefix + b64);
            return `"__DEBUG_IMG_${idx}_${sizeKB}KB__"`;
        }
    );
    // Now HTML-escape the JSON (placeholders are safe ASCII)
    let html = escapeHtml(placeholder);
    // Replace placeholders with hoverable image thumbnails
    html = html.replace(/__DEBUG_IMG_(\d+)_([\d.]+KB)__/g, (match, idx, size) => {
        const src = images[parseInt(idx)];
        return `<span class="debug-image-placeholder" onmouseenter="this.querySelector('.debug-image-tooltip').style.display='block'" onmouseleave="this.querySelector('.debug-image-tooltip').style.display='none'">[image ${size}]<span class="debug-image-tooltip"><img src="${src}"></span></span>`;
    });
    return html;
}

function loadDebugMessages() {
    const calls = debugHistory[activeTabId] || [];

    if (calls.length === 0) {
        debugContent.innerHTML = '<div style="padding: 10px; color: var(--text-secondary);">No LLM calls recorded yet.<br><br>Send a message in this tab to see the call history here.</div>';
        return;
    }

    debugContent.innerHTML = calls.map((call, i) => {
        const isLast = i === calls.length - 1;
        const arrow = isLast ? '▼' : '▶';
        const display = isLast ? 'block' : 'none';
        const msgCount = call.input ? call.input.length : 0;

        const inputHtml = call.input ? formatDebugJson(call.input) : '<em>No input</em>';

        let outputHtml;
        if (call.error) {
            outputHtml = `<span style="color: #d32f2f;">${escapeHtml(call.error)}</span>`;
        } else if (call.output) {
            outputHtml = formatDebugJson(call.output);
        } else {
            outputHtml = '<em>Pending...</em>';
        }

        return `<div class="debug-call-item${isLast ? ' expanded' : ''}" id="callitem-${i}"><div class="debug-call-header" onclick="toggleDebugCall(${i})"><span class="debug-call-arrow" id="arrow-${i}">${arrow}</span><span class="debug-call-title">Call #${i + 1}</span><span class="debug-call-time">${call.timestamp}</span></div><div class="debug-call-content" id="call-${i}" style="display: ${display};"><div class="debug-section-label">INPUT (${msgCount} messages)</div><pre>${inputHtml}</pre><div class="debug-section-label">OUTPUT</div><pre>${outputHtml}</pre></div></div>`;
    }).join('');
}

// Toggle debug call expansion
window.toggleDebugCall = function(index) {
    const content = document.getElementById(`call-${index}`);
    const arrow = document.getElementById(`arrow-${index}`);
    const item = document.getElementById(`callitem-${index}`);
    if (content.style.display === 'none') {
        content.style.display = 'block';
        arrow.textContent = '▼';
        item.classList.add('expanded');
    } else {
        content.style.display = 'none';
        arrow.textContent = '▶';
        item.classList.remove('expanded');
    }
}

// ============= SETTINGS PANEL =============

const settingsPanel = document.getElementById('settingsPanel');
const settingsPanelBody = document.getElementById('settingsPanelBody');
const settingsPanelClose = document.getElementById('settingsPanelClose');
const settingsBtn = document.getElementById('settingsBtn');
const appContainer = document.querySelector('.app-container');


// Open settings panel when SETTINGS button is clicked
if (settingsBtn) {
    settingsBtn.addEventListener('click', () => {
        closeAllPanels();
        openSettings();
        settingsPanel.classList.add('active');
        settingsBtn.classList.add('active');
        appContainer.classList.add('panel-open');
    });
}

// Close settings panel
if (settingsPanelClose) {
    settingsPanelClose.addEventListener('click', () => {
        settingsPanel.classList.remove('active');
        settingsBtn.classList.remove('active');
        appContainer.classList.remove('panel-open');
    });
}


// ============= FILES PANEL =============

const filesPanel = document.getElementById('filesPanel');
const filesPanelClose = document.getElementById('filesPanelClose');
const filesBtn = document.getElementById('filesBtn');
const fileTree = document.getElementById('fileTree');
const showHiddenFiles = document.getElementById('showHiddenFiles');
const filesRefresh = document.getElementById('filesRefresh');
const filesUpload = document.getElementById('filesUpload');

// Track expanded folder paths to preserve state on refresh
let expandedPaths = new Set();
let filesRoot = '';

// Load file tree from API
async function loadFileTree() {
    const showHidden = showHiddenFiles?.checked || false;
    try {
        const response = await apiFetch(`/api/files?show_hidden=${showHidden}`);
        if (response.ok) {
            const data = await response.json();
            filesRoot = data.root;
            renderFileTree(data.tree, fileTree, data.root);
        } else {
            fileTree.innerHTML = '<div class="files-loading">Failed to load files</div>';
        }
    } catch (e) {
        console.error('Failed to load file tree:', e);
        fileTree.innerHTML = '<div class="files-loading">Failed to load files</div>';
    }
}

// Render file tree recursively
function renderFileTree(tree, container, rootPath) {
    container.innerHTML = '';
    const rootWrapper = document.createElement('div');
    rootWrapper.className = 'file-tree-root';

    // Add header with folder name
    const header = document.createElement('div');
    header.className = 'file-tree-header';
    const folderName = rootPath.split('/').pop() || rootPath;
    header.textContent = './' + folderName;
    rootWrapper.appendChild(header);

    // Container with vertical line
    const treeContainer = document.createElement('div');
    treeContainer.className = 'file-tree-container';
    renderTreeItems(tree, treeContainer);
    rootWrapper.appendChild(treeContainer);

    container.appendChild(rootWrapper);
}

function renderTreeItems(tree, container) {
    const len = tree.length;
    for (let i = 0; i < len; i++) {
        const item = tree[i];
        const isLast = (i === len - 1);

        const itemEl = document.createElement('div');
        itemEl.className = `file-tree-item ${item.type}`;
        if (isLast) itemEl.classList.add('last');
        itemEl.dataset.path = item.path;

        // Check if this folder was previously expanded
        const wasExpanded = expandedPaths.has(item.path);

        // Create the clickable line element
        const lineEl = document.createElement('div');
        lineEl.className = 'file-tree-line';
        lineEl.draggable = true;

        // Only folders get an icon (arrow), files get empty icon
        const icon = item.type === 'folder' ? (wasExpanded ? '▼' : '▶') : '';
        const actionBtn = item.type === 'file'
            ? '<button class="file-tree-action-btn file-download-btn" title="Download">↓</button>'
            : '<button class="file-tree-action-btn file-upload-btn" title="Upload file here">+</button>';
        lineEl.innerHTML = `
            <span class="file-tree-icon">${icon}</span>
            <span class="file-tree-name">${item.name}</span>
            <span class="file-tree-actions">${actionBtn}</span>
        `;
        itemEl.appendChild(lineEl);

        // Download button (files)
        const downloadBtn = lineEl.querySelector('.file-download-btn');
        if (downloadBtn) {
            downloadBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                window.open(`/api/files/download?path=${encodeURIComponent(item.path)}${SESSION_ID ? '&session_id=' + encodeURIComponent(SESSION_ID) : ''}`, '_blank');
            });
        }

        // Upload button (folders)
        const uploadBtn = lineEl.querySelector('.file-upload-btn');
        if (uploadBtn) {
            uploadBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                const input = document.createElement('input');
                input.type = 'file';
                input.addEventListener('change', async () => {
                    if (!input.files.length) return;
                    const formData = new FormData();
                    formData.append('file', input.files[0]);
                    try {
                        await apiFetch(`/api/files/upload?folder=${encodeURIComponent(item.path)}`, {
                            method: 'POST',
                            body: formData
                        });
                        loadFileTree();
                    } catch (err) {
                        console.error('Upload failed:', err);
                    }
                });
                input.click();
            });
        }

        container.appendChild(itemEl);

        // Handle folder expansion
        if (item.type === 'folder' && item.children && item.children.length > 0) {
            const childrenContainer = document.createElement('div');
            childrenContainer.className = 'file-tree-children';
            if (wasExpanded) {
                childrenContainer.classList.add('expanded');
                itemEl.classList.add('expanded');
            }
            renderTreeItems(item.children, childrenContainer);
            itemEl.appendChild(childrenContainer);

            // Use click delay to distinguish single vs double click
            let clickTimer = null;
            lineEl.addEventListener('click', (e) => {
                e.stopPropagation();
                if (clickTimer) {
                    // Double click detected - clear timer and expand/collapse
                    clearTimeout(clickTimer);
                    clickTimer = null;
                    const isExpanded = itemEl.classList.toggle('expanded');
                    childrenContainer.classList.toggle('expanded');
                    const iconEl = lineEl.querySelector('.file-tree-icon');
                    if (iconEl) iconEl.textContent = isExpanded ? '▼' : '▶';
                    if (isExpanded) {
                        expandedPaths.add(item.path);
                    } else {
                        expandedPaths.delete(item.path);
                    }
                } else {
                    // Single click - wait to see if it's a double click
                    clickTimer = setTimeout(() => {
                        clickTimer = null;
                        insertPathIntoInput('./' + item.path);
                        showClickFeedback(lineEl);
                    }, 250);
                }
            });
        } else if (item.type === 'file') {
            // Single click on file inserts path
            lineEl.addEventListener('click', (e) => {
                e.stopPropagation();
                insertPathIntoInput('./' + item.path);
                showClickFeedback(lineEl);
            });
        }

        // Drag start handler for future drag-and-drop
        lineEl.addEventListener('dragstart', (e) => {
            e.dataTransfer.setData('text/plain', './' + item.path);
            e.dataTransfer.setData('application/x-file-path', './' + item.path);
            e.dataTransfer.effectAllowed = 'copy';
        });
    }
}

// Helper to insert path into active input
function insertPathIntoInput(path) {
    const inputId = activeTabId === 0 ? 'input-command' : `input-${activeTabId}`;
    const inputEl = document.getElementById(inputId);
    if (inputEl) {
        const start = inputEl.selectionStart;
        const end = inputEl.selectionEnd;
        const text = inputEl.value;
        // Wrap path in backticks and add trailing space
        const formattedPath = '`' + path + '` ';
        inputEl.value = text.substring(0, start) + formattedPath + text.substring(end);
        inputEl.focus();
        inputEl.selectionStart = inputEl.selectionEnd = start + formattedPath.length;
    }
}

// Linkify inline code elements that match existing file paths
async function linkifyFilePaths(container) {
    // Find all inline <code> elements (not inside <pre>)
    const codeEls = [...container.querySelectorAll('code')].filter(c => !c.closest('pre'));
    if (codeEls.length === 0) return;

    // Collect candidate paths (must look like a file path)
    const candidates = new Map(); // normalized path -> code element(s)
    for (const code of codeEls) {
        const text = code.textContent.trim();
        if (!text || text.includes(' ') || text.length > 200) continue;
        // Must contain a dot (extension) or slash (directory)
        if (!text.includes('.') && !text.includes('/')) continue;
        const normalized = text.replace(/^\.\//, '');
        if (!candidates.has(normalized)) candidates.set(normalized, []);
        candidates.get(normalized).push(code);
    }
    if (candidates.size === 0) return;

    // Check which paths exist on the server
    try {
        const resp = await apiFetch('/api/files/check', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ paths: [...candidates.keys()] })
        });
        if (!resp.ok) return;
        const { existing } = await resp.json();

        for (const path of existing) {
            for (const code of candidates.get(path) || []) {
                if (code.closest('.file-path-link')) continue; // already linked
                const link = document.createElement('a');
                link.className = 'file-path-link';
                link.href = '#';
                link.title = 'Open in file explorer';
                link.addEventListener('click', (e) => {
                    e.preventDefault();
                    navigateToFileInExplorer(path);
                });
                code.parentNode.insertBefore(link, code);
                link.appendChild(code);
            }
        }
    } catch (e) {
        // Silently fail — linkification is a nice-to-have
    }
}

// Helper to show click feedback
function showClickFeedback(el) {
    const originalColor = el.style.color;
    el.style.color = 'var(--theme-accent)';
    setTimeout(() => {
        el.style.color = originalColor;
    }, 300);
}

// Navigate to a file in the file explorer and highlight it
function navigateToFileInExplorer(path) {
    let relPath = path.replace(/^\.\//, '');

    // Open files panel if not already open
    if (!filesPanel.classList.contains('active')) {
        filesBtn.click();
    }

    // Wait for tree to render, then expand parents and highlight
    setTimeout(() => {
        const segments = relPath.split('/');
        let currentPath = '';
        for (let i = 0; i < segments.length - 1; i++) {
            currentPath += (i > 0 ? '/' : '') + segments[i];
            const folderItem = fileTree.querySelector(`.file-tree-item[data-path="${currentPath}"]`);
            if (folderItem && !folderItem.classList.contains('expanded')) {
                folderItem.classList.add('expanded');
                const children = folderItem.querySelector('.file-tree-children');
                if (children) children.classList.add('expanded');
                const icon = folderItem.querySelector('.file-tree-icon');
                if (icon) icon.textContent = '▼';
                expandedPaths.add(currentPath);
            }
        }
        const targetItem = fileTree.querySelector(`.file-tree-item[data-path="${relPath}"]`);
        if (targetItem) {
            targetItem.scrollIntoView({ behavior: 'smooth', block: 'center' });
            const line = targetItem.querySelector('.file-tree-line');
            if (line) {
                line.classList.add('file-tree-highlight');
                setTimeout(() => line.classList.remove('file-tree-highlight'), 2000);
            }
        }
    }, 500);
}

// Open files panel when FILES button is clicked
if (filesBtn) {
    filesBtn.addEventListener('click', () => {
        const isOpening = !filesPanel.classList.contains('active');
        closeAllPanels();

        if (isOpening) {
            filesPanel.classList.add('active');
            filesBtn.classList.add('active');
            appContainer.classList.add('files-panel-open');
            loadFileTree();
        }
    });
}

// Close files panel
if (filesPanelClose) {
    filesPanelClose.addEventListener('click', () => {
        filesPanel.classList.remove('active');
        filesBtn.classList.remove('active');
        appContainer.classList.remove('files-panel-open');
    });
}

// Refresh button
if (filesRefresh) {
    filesRefresh.addEventListener('click', () => {
        loadFileTree();
    });
}

// Upload to root directory
if (filesUpload) {
    filesUpload.addEventListener('click', () => {
        const input = document.createElement('input');
        input.type = 'file';
        input.addEventListener('change', async () => {
            if (!input.files.length) return;
            const formData = new FormData();
            formData.append('file', input.files[0]);
            try {
                await apiFetch('/api/files/upload?folder=', { method: 'POST', body: formData });
                loadFileTree();
            } catch (err) {
                console.error('Upload failed:', err);
            }
        });
        input.click();
    });
}

// Show hidden files toggle
if (showHiddenFiles) {
    showHiddenFiles.addEventListener('change', () => {
        loadFileTree();
    });
}

// Drag & drop upload on files panel
if (fileTree) {
    let dragOverFolder = null;

    fileTree.addEventListener('dragover', (e) => {
        // Only handle external file drops (not internal path drags)
        if (!e.dataTransfer.types.includes('Files')) return;
        e.preventDefault();
        e.dataTransfer.dropEffect = 'copy';

        // Find folder under cursor
        const folderItem = e.target.closest('.file-tree-item.folder');
        if (folderItem) {
            if (dragOverFolder !== folderItem) {
                if (dragOverFolder) dragOverFolder.classList.remove('drag-over');
                fileTree.classList.remove('drag-over-root');
                folderItem.classList.add('drag-over');
                dragOverFolder = folderItem;
            }
        } else {
            if (dragOverFolder) { dragOverFolder.classList.remove('drag-over'); dragOverFolder = null; }
            fileTree.classList.add('drag-over-root');
        }
    });

    fileTree.addEventListener('dragleave', (e) => {
        // Only clear when leaving the fileTree entirely
        if (!fileTree.contains(e.relatedTarget)) {
            if (dragOverFolder) { dragOverFolder.classList.remove('drag-over'); dragOverFolder = null; }
            fileTree.classList.remove('drag-over-root');
        }
    });

    fileTree.addEventListener('drop', async (e) => {
        if (!e.dataTransfer.files.length) return;
        e.preventDefault();

        // Determine target folder
        const folderItem = e.target.closest('.file-tree-item.folder');
        const folder = folderItem ? folderItem.dataset.path : '';

        // Clear highlights
        if (dragOverFolder) { dragOverFolder.classList.remove('drag-over'); dragOverFolder = null; }
        fileTree.classList.remove('drag-over-root');

        // Upload all files
        for (const file of e.dataTransfer.files) {
            const formData = new FormData();
            formData.append('file', file);
            try {
                await apiFetch(`/api/files/upload?folder=${encodeURIComponent(folder)}`, { method: 'POST', body: formData });
            } catch (err) {
                console.error('Upload failed:', err);
            }
        }
        loadFileTree();
    });
}

// Sessions panel (same pattern as Files/Settings/Debug panels)
const sessionsPanel = document.getElementById('sessionsPanel');
const sessionsPanelClose = document.getElementById('sessionsPanelClose');
const sessionsBtn = document.getElementById('sessionsBtn');

if (sessionsBtn && sessionsPanel) {
    sessionsBtn.addEventListener('click', () => {
        const isOpening = !sessionsPanel.classList.contains('active');
        closeAllPanels();

        if (isOpening) {
            sessionsPanel.classList.add('active');
            sessionsBtn.classList.add('active');
            appContainer.classList.add('sessions-panel-open');
            refreshSessionsList();
        }
    });
}

if (sessionsPanelClose) {
    sessionsPanelClose.addEventListener('click', () => {
        sessionsPanel.classList.remove('active');
        sessionsBtn.classList.remove('active');
        appContainer.classList.remove('sessions-panel-open');
    });
}