File size: 22,260 Bytes
25fd1e9
3589760
 
 
5cb8e2c
 
 
 
 
 
 
 
 
 
 
ac3107a
 
bb06deb
34104e6
07044b4
bbfdaf1
ac3107a
25fd1e9
ac3107a
 
 
 
 
 
 
 
 
25fd1e9
 
ac3107a
25fd1e9
921b162
 
 
 
 
 
 
 
07044b4
921b162
07044b4
 
 
921b162
 
 
 
07044b4
34104e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac3107a
656059f
ac3107a
07044b4
34104e6
07044b4
 
 
 
3589760
25fd1e9
34104e6
07044b4
34104e6
07044b4
ac3107a
 
 
 
 
07044b4
25fd1e9
5b4b486
25fd1e9
07044b4
eb69de5
 
 
 
25fd1e9
ac3107a
 
25fd1e9
5b4b486
 
 
 
 
996fe90
5b4b486
 
 
 
 
 
 
 
ac3107a
5b4b486
 
 
996fe90
5b4b486
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25fd1e9
3589760
ac3107a
5b4b486
ac3107a
5b4b486
 
 
 
3589760
 
ac3107a
 
5b4b486
 
 
 
 
 
 
 
 
 
 
 
25fd1e9
 
ac3107a
 
5b4b486
 
 
 
 
 
 
 
 
 
 
 
 
eb69de5
25fd1e9
 
ac3107a
5b4b486
 
 
ac3107a
 
5b4b486
ac3107a
25fd1e9
 
07044b4
5b4b486
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6243bd8
34104e6
 
 
 
 
 
 
 
921b162
 
07044b4
34104e6
 
 
 
 
 
 
 
 
f949ee8
34104e6
 
 
 
 
 
5b4b486
34104e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f949ee8
34104e6
f949ee8
996fe90
f949ee8
34104e6
 
 
6243bd8
 
34104e6
 
 
 
 
 
996fe90
34104e6
996fe90
 
34104e6
996fe90
 
07044b4
 
996fe90
34104e6
 
996fe90
 
 
 
 
950fad2
 
 
34104e6
950fad2
 
 
 
 
 
 
 
 
 
 
996fe90
07044b4
950fad2
 
921b162
950fad2
921b162
07044b4
921b162
07044b4
 
34104e6
 
 
 
f949ee8
34104e6
 
 
 
 
 
 
07044b4
 
34104e6
 
 
 
 
 
 
 
 
 
921b162
34104e6
 
eb69de5
34104e6
6243bd8
921b162
 
 
 
 
 
 
 
 
ac3107a
5b4b486
 
 
 
 
eb69de5
 
 
 
 
 
 
 
 
 
 
 
 
5cb8e2c
e323945
08f236e
5b4b486
 
 
 
 
eb69de5
5b4b486
eb69de5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5cb8e2c
25fd1e9
07044b4
ac3107a
5cb8e2c
eb69de5
 
 
 
07044b4
eb69de5
25fd1e9
 
5b4b486
ac3107a
 
 
 
5b4b486
 
 
 
07044b4
5b4b486
 
 
 
 
 
 
07044b4
5b4b486
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb69de5
5b4b486
ac3107a
3589760
 
eb69de5
 
07044b4
656059f
5b4b486
eb69de5
5b4b486
25fd1e9
 
 
 
eb69de5
 
 
 
 
 
 
25fd1e9
 
 
eb69de5
921b162
 
 
eb69de5
ac3107a
 
25fd1e9
 
 
eb69de5
 
 
 
 
 
25fd1e9
 
5b4b486
 
eb69de5
5b4b486
eb69de5
25fd1e9
 
 
5cb8e2c
 
 
 
 
5b4b486
5cb8e2c
 
5b4b486
921b162
5cb8e2c
 
ac3107a
 
 
 
07044b4
25fd1e9
 
ac3107a
25fd1e9
08f236e
34104e6
bbfdaf1
 
34104e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbfdaf1
 
 
34104e6
bbfdaf1
 
 
 
 
 
 
 
 
e323945
5cb8e2c
 
 
921b162
5cb8e2c
 
 
 
 
 
 
 
 
 
eb69de5
5cb8e2c
 
 
eb69de5
 
08f236e
5cb8e2c
 
 
 
 
 
 
08f236e
 
3589760
ac3107a
 
eb69de5
ac3107a
 
 
 
 
eb69de5
 
 
 
ac3107a
 
 
 
 
 
656059f
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
import { useState, useEffect, useRef } from "react";
import Editor from "@monaco-editor/react";
import { askAgent } from "./agent/assistant";
import { runCode } from "./agent/runner";
import {
  loadTree,
  saveTree,
  addFile,
  addFolder,
  renameNode,
  deleteNode,
  getNodeByPath,
  updateFileContent,
  searchTree,
} from "./fileStore";
import { downloadProjectZip } from "./zipExport";
import { parseProblems } from "./problemParser";
import "./App.css";
import "xterm/css/xterm.css";
import XTerm from "./Terminal"; // your xterm wrapper component

// =================== SUPPORTED LANGUAGES ===================
const LANGUAGE_OPTIONS = [
  { id: "python", ext: ".py", icon: "🐍", monaco: "python" },
  { id: "javascript", ext: ".js", icon: "🟨", monaco: "javascript" },
  { id: "typescript", ext: ".ts", icon: "🟦", monaco: "typescript" },
  { id: "cpp", ext: ".cpp", icon: "πŸ’ ", monaco: "cpp" },
  { id: "c", ext: ".c", icon: "πŸ”·", monaco: "c" },
  { id: "java", ext: ".java", icon: "β˜•", monaco: "java" },
  { id: "html", ext: ".html", icon: "🌐", monaco: "html" },
  { id: "css", ext: ".css", icon: "🎨", monaco: "css" },
  { id: "json", ext: ".json", icon: "🧾", monaco: "json" },
];

const RUNNABLE_LANGS = ["python", "javascript", "java"];

// Utility: detect whether output likely requests input
function outputLooksForInput(output) {
  if (!output) return false;
  const o = output.toString();
  const patterns = [
    /enter.*:/i,
    /input.*:/i,
    /please enter/i,
    /scanner/i,
    /press enter/i,
    /: $/,
    /:\n$/,
    /> $/,
  ];
  return patterns.some((p) => p.test(o));
}

// Heuristic: detect input calls inside source
function codeNeedsInput(code, langId) {
  if (!code) return false;
  try {
    const c = code.toString();
    if (langId === "python") {
      return /\binput\s*\(/i.test(c);
    }
    if (langId === "java") {
      return /\bScanner\s*\(|\bnext(Int|Line|Double)\b/i.test(c) || /\bSystem\.console\(\)/i.test(c);
    }
    if (langId === "javascript") {
      return /process\.stdin|readline|prompt\(|window\.prompt/i.test(c);
    }
    return /\binput\b|\bScanner\b|\bnextInt\b|prompt\(/i.test(c);
  } catch {
    return false;
  }
}

// =================== APP ===================
function App() {
  const [tree, setTree] = useState(loadTree());
  const [activePath, setActivePath] = useState("main.py");

  // Terminal state
  const [accumStdin, setAccumStdin] = useState("");
  const [awaitingInput, setAwaitingInput] = useState(false);
  const [output, setOutput] = useState("");
  const [prompt, setPrompt] = useState("");
  const [explanation, setExplanation] = useState("");

  // legacy and other UI
  const [terminalInput, setTerminalInput] = useState("");
  const [stdin, setStdin] = useState("");
  const [problems, setProblems] = useState([]);
  const [theme, setTheme] = useState("vs-dark");
  const [searchOpen, setSearchOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  const [aiSuggestions, setAiSuggestions] = useState([]);
  const [contextMenu, setContextMenu] = useState(null);
  const editorRef = useRef(null);
  const fileInputRef = useRef(null);

  // loading flags
  const [isRunning, setIsRunning] = useState(false);
  const [isFixing, setIsFixing] = useState(false);
  const [isExplaining, setIsExplaining] = useState(false);

  useEffect(() => {
    saveTree(tree);
  }, [tree]);

  const currentNode = getNodeByPath(tree, activePath);
  const langMeta =
    LANGUAGE_OPTIONS.find((l) => currentNode?.name?.endsWith(l.ext)) ||
    LANGUAGE_OPTIONS[0];

  // ---------- TREE helpers ----------
  const collectFolderPaths = (node, acc = []) => {
    if (!node) return acc;
    if (node.type === "folder") acc.push(node.path || "");
    node.children?.forEach((c) => collectFolderPaths(c, acc));
    return acc;
  };

  // ---------- File / Folder actions ----------
  const handleNewFile = () => {
    const filename = window.prompt("Filename (with extension):", "untitled.js");
    if (!filename) return;

    // Determine default parent
    const selected = getNodeByPath(tree, activePath);
    let parentPath = "";
    if (selected?.type === "folder") parentPath = selected.path;
    else if (selected?.type === "file") {
      const parts = selected.path.split("/").slice(0, -1);
      parentPath = parts.join("/");
    }

    const folders = collectFolderPaths(tree);
    const suggestion = parentPath || folders[0] || "";
    const chosen = window.prompt(
      `Parent folder (enter path). Available:\n${folders.join("\n")}\n\nLeave empty for root.`,
      suggestion
    );
    const targetParent = chosen == null ? parentPath : (chosen.trim() || "");

    const updated = addFile(tree, filename, targetParent);
    setTree(updated);

    const newPath = (targetParent ? targetParent + "/" : "") + filename;
    setActivePath(newPath);
  };

  const handleNewFolder = () => {
    const name = window.prompt("Folder name:", "new_folder");
    if (!name) return;
    const selected = getNodeByPath(tree, activePath);
    const parentPath = selected && selected.type === "folder" ? selected.path : "";
    const updated = addFolder(tree, name, parentPath);
    setTree(updated);
  };

  const handleRename = () => {
    if (!activePath) return;
    const node = getNodeByPath(tree, activePath);
    if (!node) return;
    const newName = window.prompt("New name:", node.name);
    if (!newName || newName === node.name) return;
    const updated = renameNode(tree, activePath, newName);
    setTree(updated);

    const parts = activePath.split("/");
    parts.pop();
    const parent = parts.join("/");
    const newPath = (parent ? parent + "/" : "") + newName;
    setActivePath(newPath);
  };

  const handleDelete = () => {
    if (!activePath) return;
    const node = getNodeByPath(tree, activePath);
    if (!node) return;

    if (node.type === "folder" && node.children?.length > 0) {
      const ok = window.confirm(`Folder "${node.name}" has ${node.children.length} items. Delete anyway?`);
      if (!ok) return;
    } else {
      const ok = window.confirm(`Delete "${node.name}"?`);
      if (!ok) return;
    }

    const updated = deleteNode(tree, activePath);
    setTree(updated);
    setActivePath("");
  };

  const downloadFile = () => {
    const node = getNodeByPath(tree, activePath);
    if (!node || node.type !== "file") return;
    const blob = new Blob([node.content || ""], { type: "text/plain;charset=utf-8" });
    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.download = node.name;
    a.click();
  };

  // import file
  const handleImportFileClick = () => fileInputRef.current?.click();

  const handleFileInputChange = async (e) => {
    const f = e.target.files?.[0];
    if (!f) return;
    const text = await f.text();

    const selected = getNodeByPath(tree, activePath);
    let parentPath = "";
    if (selected?.type === "folder") parentPath = selected.path;
    else if (selected?.type === "file") parentPath = selected.path.split("/").slice(0, -1).join("");

    const updated = addFile(tree, f.name, parentPath);
    const newPath = (parentPath ? parentPath + "/" : "") + f.name;
    const finalTree = updateFileContent(updated, newPath, text);
    setTree(finalTree);
    setActivePath(newPath);
    e.target.value = "";
  };

  // ---------- Terminal helpers ----------
  const resetTerminal = (keepAccum = false) => {
    setOutput("");
    if (!keepAccum) {
      setAccumStdin("");
    }
    setAwaitingInput(false);
    setTerminalInput("");
  };

  // On-line input from XTerm -> append and re-run
  const runCodeWithUpdatedInput = async (inputLine) => {
    const newAccum = (accumStdin || "") + inputLine + "\n";
    setAccumStdin(newAccum);

    const node = getNodeByPath(tree, activePath);
    if (!node || node.type !== "file") {
      setOutput((prev) => prev + "\n[Error] No file selected to run.");
      setAwaitingInput(false);
      return;
    }

    const selectedLang = LANGUAGE_OPTIONS.find((l) => node.name.endsWith(l.ext))?.id;
    if (!selectedLang || !RUNNABLE_LANGS.includes(selectedLang)) {
      setOutput((prev) => prev + `\n[Error] Run not supported for ${node.name}`);
      setAwaitingInput(false);
      return;
    }

    setIsRunning(true);
    try {
      const res = await runCode(node.content, selectedLang, newAccum);
      const out = res.output ?? "";
      setOutput(out);
      setProblems(res.error ? parseProblems(res.output) : []);
      if (outputLooksForInput(out)) {
        setAwaitingInput(true);
      } else {
        setAwaitingInput(false);
      }
    } catch (err) {
      setOutput(String(err));
      setAwaitingInput(false);
    } finally {
      setIsRunning(false);
    }
  };

  // Initial run β€” DO NOT call run if code needs interactive input and we have no accumStdin.
  const handleRun = async () => {
    const node = getNodeByPath(tree, activePath);
    if (!node || node.type !== "file") {
      setOutput("Select a file to run.");
      return;
    }
    const selectedLang = LANGUAGE_OPTIONS.find((l) => node.name.endsWith(l.ext))?.id;
    if (!selectedLang || !RUNNABLE_LANGS.includes(selectedLang)) {
      setOutput(`⚠️ Run not supported for this file type.`);
      return;
    }

    // If code likely needs input and we have no accumulated stdin, don't run β€” wait for user input in XTerm.
    const needs = codeNeedsInput(node.content, selectedLang);
    const haveAccum = !!(accumStdin && accumStdin.length > 0);
    const haveLegacyStdin = !!(stdin && stdin.length > 0);

    if (needs && !haveAccum && !haveLegacyStdin) {
      // Show helpful message in terminal and enable awaitingInput so user can type into XTerm.
      setOutput("[Interactive program detected β€” type input directly into the terminal]");
      setAwaitingInput(true);
      return; // <-- important: do NOT run now
    }

    // Otherwise run immediately with whichever stdin we have (accumStdin or legacy stdin)
    const stdinToSend = accumStdin || stdin || "";

    resetTerminal(true); // keep accumStdin
    setOutput(`[Running with stdin length=${stdinToSend ? stdinToSend.length : 0}]\n`);
    setIsRunning(true);
    setProblems([]);
    try {
      const res = await runCode(node.content, selectedLang, stdinToSend);
      const out = res.output ?? "";
      setOutput(out);
      setProblems(res.error ? parseProblems(res.output) : []);
      if (outputLooksForInput(out)) {
        setAwaitingInput(true);
      } else {
        setAwaitingInput(false);
      }
    } catch (err) {
      const e = String(err);
      setOutput(e);
      // Allow user to type into terminal after EOF errors
      setAwaitingInput(true);
    } finally {
      setIsRunning(false);
    }
  };

  // Legacy send from input box
  const sendTerminalInput = async () => {
    const node = getNodeByPath(tree, activePath);
    if (!node || node.type !== "file") {
      setOutput((prev) => prev + "\nNo file selected.");
      setAwaitingInput(false);
      return;
    }

    const userText = terminalInput;
    setOutput((prev) => prev + `\n> ${userText}`);
    const newAccum = (accumStdin || "") + userText + "\n";
    setAccumStdin(newAccum);
    setTerminalInput("");
    setIsRunning(true);
    try {
      const selectedLang = LANGUAGE_OPTIONS.find((l) => node.name.endsWith(l.ext))?.id;
      const res = await runCode(node.content, selectedLang, newAccum);
      const out = res.output ?? "";
      setOutput(out);
      setProblems(res.error ? parseProblems(res.output) : []);
      if (outputLooksForInput(out)) {
        setAwaitingInput(true);
      } else {
        setAwaitingInput(false);
      }
    } catch (err) {
      setOutput((prev) => prev + "\n" + String(err));
      setAwaitingInput(false);
    } finally {
      setIsRunning(false);
    }
  };

  const onTerminalKeyDown = (e) => {
    if (e.key === "Enter") {
      e.preventDefault();
      if (!awaitingInput) return;
      sendTerminalInput();
    }
  };

  // ---------- Agent functions ----------
  const handleAskFix = async () => {
    const node = getNodeByPath(tree, activePath);
    if (!node || node.type !== "file") {
      setOutput("Select a file to apply fix.");
      return;
    }
    setIsFixing(true);
    try {
      const userHint = prompt.trim() ? `User request: ${prompt}` : "";
      const reply = await askAgent(
        `Improve, debug, or refactor this ${LANGUAGE_OPTIONS.find((l) => node.name.endsWith(l.ext))?.id || "file"} file.\n${userHint}\nReturn ONLY updated code, no explanation.\n\nCODE:\n${node.content}`
      );
      const updatedTree = updateFileContent(tree, node.path, reply);
      setTree(updatedTree);
    } catch (err) {
      setOutput(String(err));
    } finally {
      setIsFixing(false);
    }
  };

  const handleExplainSelection = async () => {
    const node = getNodeByPath(tree, activePath);
    if (!node || node.type !== "file") {
      setExplanation("Select a file to explain.");
      return;
    }
    setIsExplaining(true);
    try {
      const editor = editorRef.current;
      let selectedCode = "";
      try {
        selectedCode = editor?.getModel()?.getValueInRange(editor.getSelection()) || "";
      } catch {}
      const code = selectedCode.trim() || node.content;
      const userHint = prompt.trim() ? `Focus on: ${prompt}` : "Give a clear and simple explanation.";
      const reply = await askAgent(
        `Explain what this code does, any risks, and improvements.\n${userHint}\n\nCODE:\n${code}`
      );
      setExplanation(reply);
    } catch (err) {
      setExplanation(String(err));
    } finally {
      setIsExplaining(false);
    }
  };

  // AI suggestions for continuation
  const fetchAiSuggestions = async (code) => {
    if (!code?.trim()) return;
    try {
      const reply = await askAgent(`Suggest possible next lines for continuation. Return 3 short snippets.\n${code}`);
      setAiSuggestions(reply.split("\n").filter((l) => l.trim()));
    } catch {
      // ignore
    }
  };

  // ---------- Search ----------
  const handleSearchToggle = () => setSearchOpen(!searchOpen);

  const handleSearchNow = () => {
    if (!searchQuery) return;
    const results = searchTree(tree, searchQuery);
    alert(`Found ${results.length} results:\n` + JSON.stringify(results, null, 2));
  };

  // Editor change
  const updateActiveFileContent = (value) => {
    const node = getNodeByPath(tree, activePath);
    if (!node) return;
    const updated = updateFileContent(tree, activePath, value ?? "");
    setTree(updated);
  };

  // Render tree
  const renderTree = (node, depth = 0) => {
    const isActive = node.path === activePath;
    return (
      <div key={node.path || node.name} style={{ paddingLeft: depth * 10 }}>
        <div
          className={`tree-item ${node.type} ${isActive ? "ide-file-item-active" : ""}`}
          onClick={() => setActivePath(node.path)}
          onContextMenu={(e) => {
            e.preventDefault();
            setActivePath(node.path);
            setContextMenu({ x: e.pageX, y: e.pageY, file: node.path });
          }}
          style={{ display: "flex", alignItems: "center", gap: 8 }}
        >
          <span style={{ width: 18 }}>{node.type === "folder" ? "πŸ“" : "πŸ“„"}</span>
          <span className="ide-file-name">{node.name}</span>
        </div>

        {node.children && node.children.map((c) => renderTree(c, depth + 1))}
      </div>
    );
  };

  const anyLoading = isRunning || isFixing || isExplaining;

  // JSX
  return (
    <div className={`ide-root ${theme === "vs-dark" ? "ide-dark" : "ide-light"}`}>
      <input ref={fileInputRef} id="file-import-input" type="file" style={{ display: "none" }} onChange={handleFileInputChange} />

      <div className="ide-menubar">
        <div className="ide-menubar-left">
          <span className="ide-logo">βš™οΈ DevMate IDE</span>

          <button onClick={handleNewFile} disabled={anyLoading}>πŸ“„ New File</button>
          <button onClick={handleNewFolder} disabled={anyLoading}>πŸ“ New Folder</button>
          <button onClick={handleRename} disabled={anyLoading}>✏️ Rename</button>
          <button onClick={handleDelete} disabled={anyLoading}>πŸ—‘ Delete</button>
          <button onClick={downloadFile} disabled={anyLoading}>πŸ“₯ Download</button>
          <button onClick={() => downloadProjectZip()} disabled={anyLoading}>πŸ“¦ ZIP</button>
          <button onClick={handleImportFileClick} disabled={anyLoading}>πŸ“€ Import File</button>
        </div>

        <div className="ide-menubar-right">
          <button onClick={handleSearchToggle} disabled={anyLoading}>πŸ” Search</button>
          <button onClick={handleRun} disabled={isRunning || anyLoading}>{isRunning ? "⏳ Running..." : "β–Ά Run"}</button>
          <button onClick={handleAskFix} disabled={isFixing || anyLoading}>{isFixing ? "⏳ Fixing..." : "πŸ€– Fix"}</button>
          <button onClick={handleExplainSelection} disabled={isExplaining || anyLoading}>{isExplaining ? "⏳ Explaining..." : "πŸ“– Explain"}</button>
          <button onClick={() => setTheme((t) => (t === "vs-dark" ? "light" : "vs-dark"))} disabled={anyLoading}>
            {theme === "vs-dark" ? "β˜€οΈ" : "πŸŒ™"}
          </button>
        </div>
      </div>

      {anyLoading && (
        <div className="ide-progress-wrap">
          <div className="ide-progress" />
        </div>
      )}

      <div className="ide-body">
        <div className="ide-sidebar">
          <div className="ide-sidebar-header">
            <span>EXPLORER</span>
            <button className="ide-icon-button" onClick={handleNewFile} title="New File" disabled={anyLoading}>οΌ‹</button>
          </div>
          <div className="ide-file-list" style={{ padding: 6 }}>{renderTree(tree)}</div>
        </div>

        <div className="ide-main">
          <div className="ide-editor-wrapper">
            <Editor
              height="100%"
              theme={theme}
              language={langMeta.monaco}
              value={currentNode?.content || ""}
              onChange={updateActiveFileContent}
              onMount={(editor) => (editorRef.current = editor)}
              onBlur={() => fetchAiSuggestions(currentNode?.content)}
              options={{ minimap: { enabled: true }, fontSize: 14, scrollBeyondLastLine: false }}
            />
          </div>

          {aiSuggestions.length > 0 && (
            <div className="ai-popup">
              {aiSuggestions.map((s, i) => (
                <div key={i} className="ai-suggest" onClick={() => updateFileContent(tree, activePath, (currentNode?.content || "") + "\n" + s)}>{s}</div>
              ))}
            </div>
          )}

          <div className="ide-panels">
            <div style={{ marginBottom: 8 }}>
              <div style={{ fontSize: 12, color: "#ccc", marginBottom: 6 }}>Terminal</div>

              <XTerm
                output={output}
                onData={(line) => {
                  runCodeWithUpdatedInput(line);
                }}
              />

              {!awaitingInput && (
                <div style={{ display: "flex", gap: 6, marginTop: 6 }}>
                  <input className="ide-input-box" placeholder="(Optional) Program input for single-run" value={stdin} onChange={(e) => setStdin(e.target.value)} />
                  <div style={{ alignSelf: "center", color: "#999", fontSize: 12 }}>Press Run β†’ to execute</div>
                </div>
              )}

              {awaitingInput && (
                <div style={{ display: "flex", gap: 6, marginTop: 6 }}>
                  <input
                    className="ide-input-box"
                    placeholder="Type input and press Send..."
                    value={terminalInput}
                    onChange={(e) => setTerminalInput(e.target.value)}
                    onKeyDown={onTerminalKeyDown}
                    disabled={!awaitingInput || isRunning}
                  />
                  <button onClick={sendTerminalInput} disabled={!awaitingInput || isRunning} className="ide-button">Send</button>
                </div>
              )}
            </div>

            {problems.length > 0 && (
              <div className="ide-problems-panel">
                <div>🚨 Problems ({problems.length})</div>
                {problems.map((p, i) => <div key={i}>{p.path}:{p.line} β€” {p.message}</div>)}
              </div>
            )}
          </div>
        </div>

        <div className="ide-right-panel">
          <div className="ide-ai-header">πŸ€– AI Assistant</div>

          <div className="ide-ai-section">
            <label className="ide-ai-label">Instruction</label>
            <textarea className="ide-agent-textarea" placeholder="Ask the AI (optimize, add tests, convert, etc.)" value={prompt} onChange={(e) => setPrompt(e.target.value)} />
          </div>

          <div className="ide-ai-buttons">
            <button onClick={handleAskFix} disabled={isFixing || anyLoading}>{isFixing ? "⏳ Apply Fix" : "πŸ’‘ Apply Fix"}</button>
            <button onClick={handleExplainSelection} disabled={isExplaining || anyLoading}>{isExplaining ? "⏳ Explaining" : "πŸ“– Explain Code"}</button>
          </div>

          {explanation && (
            <div className="ide-ai-section">
              <label className="ide-ai-label">Explanation</label>
              <div className="ide-explain">{explanation}</div>
            </div>
          )}
        </div>
      </div>

      {searchOpen && (
        <div className="search-dialog">
          <input placeholder="Search text..." onChange={(e) => setSearchQuery(e.target.value)} />
          <button onClick={handleSearchNow}>Search</button>
        </div>
      )}

      {contextMenu && (
        <div className="ide-context-menu" style={{ top: contextMenu.y, left: contextMenu.x }} onMouseLeave={() => setContextMenu(null)}>
          <div onClick={() => { setContextMenu(null); handleRename(); }}>✏️ Rename</div>
          <div onClick={() => { setContextMenu(null); handleDelete(); }}>πŸ—‘ Delete</div>
          <div onClick={() => { setContextMenu(null); downloadFile(); }}>πŸ“₯ Download</div>
        </div>
      )}
    </div>
  );
}

export default App;