"use client";

import { useEffect, useState, useCallback } from "react";
import TerminalConsole from "./TerminalConsole";

interface FileNode {
  name: string;
  path: string;
  type: "file" | "directory";
  children?: FileNode[];
}

interface WorkspaceData {
  name: string;
  path: string;
  tree: FileNode[];
}

interface ScopedData {
  name: string;
  path: string;
  tree: FileNode[];
}

interface GitFile {
  status: string;
  relativePath: string;
  absolutePath: string;
  name: string;
}

interface SessionStatus {
  type?: string;
  status?: string;
  logs?: string[];
  tokenUsage?: {
    input: number;
    output: number;
    cost: number;
  };
}

interface SessionStats {
  cpu: string;
  memory: string;
  memoryPercent: string;
  type?: string;
}

interface FlatFile {
  name: string;
  path: string;
  relativePath: string;
}

interface RunnerStatus {
  id: string;
  name: string;
  type: 'mock' | 'claude' | 'claude-docker' | 'claude-ssh' | 'aider' | 'aider-docker';
  status: 'idle' | 'running' | 'stopped';
  createdAt: string;
  logsCount: number;
  workspaceRoot?: string;
  scopedDirs?: string[];
}

interface IdeLayoutProps {
  sessionId: string;
  workspaceRoot: string;
  scopedDirs: string[];
  onClose: () => void;
  sessions: RunnerStatus[];
  onSwitchSession: (id: string) => void;
}

interface OpenFile {
  name: string;
  path: string;
  content: string;
  isModified: boolean;
}

export default function IdeLayout({ sessionId, workspaceRoot, scopedDirs, onClose, sessions, onSwitchSession }: IdeLayoutProps) {
  const scopedDirsStr = JSON.stringify(scopedDirs);
  const [workspace, setWorkspace] = useState<WorkspaceData | null>(null);
  const [scoped, setScoped] = useState<ScopedData[]>([]);
  
  // Track open files and active files per session to preserve state on tab swap
  const [sessionOpenFiles, setSessionOpenFiles] = useState<{ [sessionId: string]: OpenFile[] }>({});
  const [sessionActiveFiles, setSessionActiveFiles] = useState<{ [sessionId: string]: string | null }>({});

  const openFiles = sessionOpenFiles[sessionId] || [];
  const activeFilePath = sessionActiveFiles[sessionId] || null;

  const setOpenFiles = useCallback((newFiles: OpenFile[] | ((prev: OpenFile[]) => OpenFile[])) => {
    setSessionOpenFiles(prev => {
      const currentFiles = prev[sessionId] || [];
      const updatedFiles = typeof newFiles === "function" ? newFiles(currentFiles) : newFiles;
      return { ...prev, [sessionId]: updatedFiles };
    });
  }, [sessionId]);

  const setActiveFilePath = useCallback((path: string | null) => {
    setSessionActiveFiles(prev => ({ ...prev, [sessionId]: path }));
  }, [sessionId]);

  const [explorerVisible, setExplorerVisible] = useState(true);
  const [activeTab, setActiveTab] = useState<"explorer" | "git" | "analytics" | "auditor">("explorer");
  const [isRefreshing, setIsRefreshing] = useState(false);

  // Git Diff Panel state
  const [gitFiles, setGitFiles] = useState<GitFile[]>([]);
  const [isGitRepo, setIsGitRepo] = useState(false);
  const [gitLoading, setGitLoading] = useState(false);

  // Status & Telemetry
  const [sessionStatus, setSessionStatus] = useState<SessionStatus | null>(null);
  const [stats, setStats] = useState<SessionStats | null>(null);

  // Log Search & Auditor
  const [logSearchQuery, setLogSearchQuery] = useState("");

  // Custom Commands
  const [customCommands, setCustomCommands] = useState<{ name: string; command: string }[]>([]);
  const [newCmdName, setNewCmdName] = useState("");
  const [newCmdStr, setNewCmdStr] = useState("");
  
  // Console split view state
  const [splitSessionId, setSplitSessionId] = useState<string | null>(null);

  // Load Git status
  const loadGitStatus = useCallback(async () => {
    // Defer state updates to prevent synchronous execution inside useEffect
    await new Promise(resolve => setTimeout(resolve, 0));
    setGitLoading(true);
    try {
      const res = await fetch(`/api/git?action=status&root=${encodeURIComponent(workspaceRoot)}`);
      if (res.ok) {
        const data = await res.json();
        if (data.success) {
          setIsGitRepo(data.isGit);
          setGitFiles(data.files || []);
        }
      }
    } catch (e) {
      console.error("Failed to load git status:", e);
    } finally {
      setGitLoading(false);
    }
  }, [workspaceRoot]);

  useEffect(() => {
    setTimeout(() => {
      loadGitStatus();
    }, 0);
    const id = setInterval(loadGitStatus, 5000);
    return () => clearInterval(id);
  }, [loadGitStatus]);

  // Poll Session Status (logs, tokens, type)
  useEffect(() => {
    const fetchStatus = async () => {
      try {
        const res = await fetch(`/api/sessions?id=${sessionId}`);
        if (res.ok) {
          const data = await res.json();
          setSessionStatus(data);
        }
      } catch (e) {
        console.error("Failed to fetch session status:", e);
      }
    };
    fetchStatus();
    const id = setInterval(fetchStatus, 3000);
    return () => clearInterval(id);
  }, [sessionId]);

  // Poll CPU / Memory Stats
  useEffect(() => {
    const fetchStats = async () => {
      try {
        const res = await fetch(`/api/sessions/stats?id=${sessionId}`);
        if (res.ok) {
          const data = await res.json();
          setStats(data);
        }
      } catch (e) {
        console.error("Failed to fetch container/process stats:", e);
      }
    };
    fetchStats();
    const id = setInterval(fetchStats, 3000);
    return () => clearInterval(id);
  }, [sessionId]);

  // Custom Commands Persistence
  useEffect(() => {
    const saved = localStorage.getItem("neural_loom_custom_commands");
    if (saved) {
      try {
        const parsed = JSON.parse(saved);
        setTimeout(() => {
          setCustomCommands(parsed);
        }, 0);
      } catch {}
    }
  }, []);

  const saveCommands = (cmds: { name: string; command: string }[]) => {
    setCustomCommands(cmds);
    localStorage.setItem("neural_loom_custom_commands", JSON.stringify(cmds));
  };

  const handleAddCommand = () => {
    if (!newCmdName.trim() || !newCmdStr.trim()) return;
    const updated = [...customCommands, { name: newCmdName.trim(), command: newCmdStr.trim() }];
    saveCommands(updated);
    setNewCmdName("");
    setNewCmdStr("");
  };

  const handleDeleteCommand = (idx: number) => {
    const updated = customCommands.filter((_, i) => i !== idx);
    saveCommands(updated);
  };

  const triggerInject = async (command: string) => {
    try {
      await fetch("/api/sessions/inject", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id: sessionId, command }),
      });
    } catch (e) {
      console.error("Failed to inject command:", e);
    }
  };

  const handleExportLog = () => {
    if (!sessionStatus?.logs) return;
    const fullLog = sessionStatus.logs.join("").replace(/\x1b\[[0-9;]*m/g, "");
    const blob = new Blob([fullLog], { type: "text/plain;charset=utf-8" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `session-${sessionId}-logs.txt`;
    a.click();
    URL.revokeObjectURL(url);
  };

  const isAider = sessionStatus?.type?.includes("aider");

  // Dialog operations state
  const [dialog, setDialog] = useState<{
    type: "create-file" | "create-folder" | "rename" | "delete" | null;
    targetPath: string | null;
    inputValue: string;
    error: string | null;
  }>({ type: null, targetPath: null, inputValue: "", error: null });

  // Search modal state
  const [searchOpen, setSearchOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  const [flatFiles, setFlatFiles] = useState<FlatFile[]>([]);
  const [searchSelectedIndex, setSearchSelectedIndex] = useState(0);

  // Load directory tree
  const loadFiles = useCallback(async () => {
    // Defer state updates to prevent synchronous execution inside useEffect
    await new Promise(resolve => setTimeout(resolve, 0));
    setIsRefreshing(true);
    try {
      const scopedQuery = scopedDirs && scopedDirs.length > 0 ? `&scoped=${encodeURIComponent(scopedDirs.join(","))}` : "";
      const res = await fetch(`/api/files?action=list&root=${encodeURIComponent(workspaceRoot)}${scopedQuery}`);
      if (res.ok) {
        const data = await res.json();
        if (data.success) {
          setWorkspace(data.workspace);
          setScoped(data.scoped || []);
        }
      }
    } catch (err) {
      console.error("Failed to load file explorer:", err);
    } finally {
      setIsRefreshing(false);
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [workspaceRoot, scopedDirsStr]);

  useEffect(() => {
    setTimeout(() => {
      loadFiles();
    }, 0);
  }, [loadFiles]);

  // Trigger creation dialog
  const handleTriggerCreate = (parentPath: string, type: "file" | "directory") => {
    setDialog({
      type: type === "file" ? "create-file" : "create-folder",
      targetPath: parentPath,
      inputValue: "",
      error: null
    });
  };

  // Trigger rename dialog
  const handleTriggerRename = (targetPath: string) => {
    const name = targetPath.split(/[/\\]/).pop() || "";
    setDialog({
      type: "rename",
      targetPath,
      inputValue: name,
      error: null
    });
  };

  // Trigger delete dialog
  const handleTriggerDelete = (targetPath: string) => {
    setDialog({
      type: "delete",
      targetPath,
      inputValue: "",
      error: null
    });
  };

  const handleDialogSubmit = async (e?: React.FormEvent) => {
    if (e) e.preventDefault();
    if (!dialog.type || !dialog.targetPath) return;

    setDialog(prev => ({ ...prev, error: null }));

    try {
      if (dialog.type === "create-file" || dialog.type === "create-folder") {
        if (!dialog.inputValue.trim()) {
          setDialog(prev => ({ ...prev, error: "Name cannot be empty" }));
          return;
        }
        
        const newPath = `${dialog.targetPath}/${dialog.inputValue.trim()}`;
        const itemType = dialog.type === "create-file" ? "file" : "directory";

        const res = await fetch("/api/files", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            action: "create",
            path: newPath,
            type: itemType,
          }),
        });

        if (res.ok) {
          const data = await res.json();
          if (data.success) {
            setDialog({ type: null, targetPath: null, inputValue: "", error: null });
            await loadFiles();
            if (itemType === "file") {
              await handleOpenFile(newPath);
            }
          } else {
            setDialog(prev => ({ ...prev, error: data.error || "Failed to create item" }));
          }
        } else {
          const data = await res.json();
          setDialog(prev => ({ ...prev, error: data.error || "Failed to create item" }));
        }
      }

      if (dialog.type === "rename") {
        if (!dialog.inputValue.trim()) {
          setDialog(prev => ({ ...prev, error: "Name cannot be empty" }));
          return;
        }

        const normPath = dialog.targetPath.replace(/\\/g, "/");
        const parentDir = normPath.substring(0, normPath.lastIndexOf("/"));
        const newPath = parentDir ? `${parentDir}/${dialog.inputValue.trim()}` : dialog.inputValue.trim();

        const res = await fetch("/api/files", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            action: "rename",
            oldPath: dialog.targetPath,
            newPath: newPath,
          }),
        });

        if (res.ok) {
          const data = await res.json();
          if (data.success) {
            // Update openFiles state if renamed file was open
            setOpenFiles(prev => prev.map(f => {
              if (f.path === dialog.targetPath) {
                return {
                  ...f,
                  path: newPath,
                  name: dialog.inputValue.trim()
                };
              }
              return f;
            }));
            if (activeFilePath === dialog.targetPath) {
              setActiveFilePath(newPath);
            }
            setDialog({ type: null, targetPath: null, inputValue: "", error: null });
            await loadFiles();
          } else {
            setDialog(prev => ({ ...prev, error: data.error || "Failed to rename item" }));
          }
        } else {
          const data = await res.json();
          setDialog(prev => ({ ...prev, error: data.error || "Failed to rename item" }));
        }
      }

      if (dialog.type === "delete") {
        const res = await fetch("/api/files", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            action: "delete",
            path: dialog.targetPath,
          }),
        });

        if (res.ok) {
          const data = await res.json();
          if (data.success) {
            handleCloseFile(dialog.targetPath);
            setDialog({ type: null, targetPath: null, inputValue: "", error: null });
            await loadFiles();
          } else {
            setDialog(prev => ({ ...prev, error: data.error || "Failed to delete item" }));
          }
        } else {
          const data = await res.json();
          setDialog(prev => ({ ...prev, error: data.error || "Failed to delete item" }));
        }
      }
    } catch (err) {
      console.error("File operation failed:", err);
      setDialog(prev => ({ ...prev, error: "An unexpected error occurred" }));
    }
  };

  const fetchFlatFiles = useCallback(async () => {
    try {
      const scopedQuery = scopedDirs && scopedDirs.length > 0 ? `&scoped=${encodeURIComponent(scopedDirs.join(","))}` : "";
      const res = await fetch(`/api/files?action=flat_list&root=${encodeURIComponent(workspaceRoot)}${scopedQuery}`);
      if (res.ok) {
        const data = await res.json();
        if (data.success && data.files) {
          setFlatFiles(data.files);
        }
      }
    } catch (err) {
      console.error("Failed to load flat files list:", err);
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [workspaceRoot, scopedDirsStr]);

  useEffect(() => {
    if (searchOpen) {
      // Defer state updates to prevent synchronous execution inside useEffect
      setTimeout(() => {
        setSearchQuery("");
        setSearchSelectedIndex(0);
        fetchFlatFiles();
      }, 0);
    }
  }, [searchOpen, fetchFlatFiles]);

  // Handle file click in explorer
  const handleOpenFile = async (filePath: string) => {
    // Check if already open
    const alreadyOpen = openFiles.find((f) => f.path === filePath);
    if (alreadyOpen) {
      setActiveFilePath(filePath);
      return;
    }

    try {
      const res = await fetch(`/api/files?action=read&path=${encodeURIComponent(filePath)}`);
      if (res.ok) {
        const data = await res.json();
        if (data.success) {
          const newFile: OpenFile = {
            name: filePath.split(/[/\\]/).pop() || "Untitled",
            path: filePath,
            content: data.content,
            isModified: false,
          };
          setOpenFiles([...openFiles, newFile]);
          setActiveFilePath(filePath);
        }
      }
    } catch (err) {
      console.error(`Failed to read file ${filePath}:`, err);
    }
  };

  const handleCloseFile = (filePath: string) => {
    const updated = openFiles.filter((f) => f.path !== filePath);
    setOpenFiles(updated);
    if (activeFilePath === filePath) {
      setActiveFilePath(updated.length > 0 ? updated[updated.length - 1].path : null);
    }
  };

  const activeFile = openFiles.find((f) => f.path === activeFilePath);

  const handleContentChange = (newVal: string) => {
    if (!activeFilePath) return;
    setOpenFiles(
      openFiles.map((f) => (f.path === activeFilePath ? { ...f, content: newVal, isModified: true } : f))
    );
  };

  const handleSaveFile = useCallback(async () => {
    if (!activeFile) return;
    try {
      const res = await fetch("/api/files", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action: "write",
          path: activeFile.path,
          content: activeFile.content,
        }),
      });

      if (res.ok) {
        setOpenFiles(prev =>
          prev.map((f) => (f.path === activeFilePath ? { ...f, isModified: false } : f))
        );
      }
    } catch (err) {
      console.error(`Failed to save file ${activeFile.path}:`, err);
    }
  }, [activeFile, activeFilePath, setOpenFiles]);

  // Listen for Ctrl+S and Ctrl+P
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if ((e.ctrlKey || e.metaKey) && e.key === "s") {
        e.preventDefault();
        handleSaveFile();
      }
      if ((e.ctrlKey || e.metaKey) && e.key === "p") {
        e.preventDefault();
        setSearchOpen(prev => !prev);
      }
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [handleSaveFile]);


  const filteredFiles = flatFiles.filter(f => 
    f.name.toLowerCase().includes(searchQuery.toLowerCase()) || 
    f.relativePath.toLowerCase().includes(searchQuery.toLowerCase())
  ).slice(0, 10);

  const handleSearchKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "ArrowDown") {
      e.preventDefault();
      setSearchSelectedIndex(prev => (prev + 1) % Math.max(1, filteredFiles.length));
    } else if (e.key === "ArrowUp") {
      e.preventDefault();
      setSearchSelectedIndex(prev => (prev - 1 + filteredFiles.length) % Math.max(1, filteredFiles.length));
    } else if (e.key === "Enter") {
      e.preventDefault();
      if (filteredFiles[searchSelectedIndex]) {
        handleOpenFile(filteredFiles[searchSelectedIndex].path);
        setSearchOpen(false);
      }
    } else if (e.key === "Escape") {
      e.preventDefault();
      setSearchOpen(false);
    }
  };

  return (
    <div style={ideContainerStyle}>
      {/* Activity Bar (Sidebar leftmost panel icons) */}
      <div style={activityBarStyle}>
        <div style={topIconsStyle}>
          {/* Explorer Tab */}
          <div
            onClick={() => {
              if (activeTab === "explorer") {
                setExplorerVisible(!explorerVisible);
              } else {
                setActiveTab("explorer");
                setExplorerVisible(true);
              }
            }}
            style={{
              ...sidebarIconStyle,
              backgroundColor: activeTab === "explorer" && explorerVisible ? "rgba(255,255,255,0.08)" : "transparent",
              borderLeft: activeTab === "explorer" && explorerVisible ? "2px solid var(--primary)" : "2px solid transparent",
            }}
            title="File Explorer (Ctrl+P to search files)"
          >
            📁
          </div>

          {/* Git Source Control Tab */}
          <div
            onClick={() => {
              if (activeTab === "git") {
                setExplorerVisible(!explorerVisible);
              } else {
                setActiveTab("git");
                setExplorerVisible(true);
              }
            }}
            style={{
              ...sidebarIconStyle,
              backgroundColor: activeTab === "git" && explorerVisible ? "rgba(255,255,255,0.08)" : "transparent",
              borderLeft: activeTab === "git" && explorerVisible ? "2px solid var(--primary)" : "2px solid transparent",
            }}
            title="Source Control (Git Changes)"
          >
            🌿
          </div>

          {/* Token & Cost Analytics Tab */}
          <div
            onClick={() => {
              if (activeTab === "analytics") {
                setExplorerVisible(!explorerVisible);
              } else {
                setActiveTab("analytics");
                setExplorerVisible(true);
              }
            }}
            style={{
              ...sidebarIconStyle,
              backgroundColor: activeTab === "analytics" && explorerVisible ? "rgba(255,255,255,0.08)" : "transparent",
              borderLeft: activeTab === "analytics" && explorerVisible ? "2px solid var(--primary)" : "2px solid transparent",
            }}
            title="Token Usage & Cost Analytics"
          >
            📊
          </div>

          {/* Log Auditor Tab */}
          <div
            onClick={() => {
              if (activeTab === "auditor") {
                setExplorerVisible(!explorerVisible);
              } else {
                setActiveTab("auditor");
                setExplorerVisible(true);
              }
            }}
            style={{
              ...sidebarIconStyle,
              backgroundColor: activeTab === "auditor" && explorerVisible ? "rgba(255,255,255,0.08)" : "transparent",
              borderLeft: activeTab === "auditor" && explorerVisible ? "2px solid var(--primary)" : "2px solid transparent",
            }}
            title="Session Log Auditor & Search"
          >
            🔍
          </div>
        </div>

        <div
          onClick={onClose}
          style={{ ...sidebarIconStyle, color: "var(--danger)", fontSize: "1rem" }}
          title="Exit Session Layout"
        >
          ✖
        </div>
      </div>

      {/* Primary Sidebar (File Tree Panel) */}
      {explorerVisible && (
        <div style={sidebarPanelStyle}>
          <div style={sidebarHeaderStyle}>
            <span style={{ fontWeight: 700, fontSize: "0.75rem", textTransform: "uppercase", letterSpacing: "0.05em" }}>
              {activeTab === "explorer" && "Workspace Explorer"}
              {activeTab === "git" && "Source Control"}
              {activeTab === "analytics" && "Telemetry & Cost"}
              {activeTab === "auditor" && "Session Auditor"}
            </span>
            {activeTab === "explorer" && (
              <div style={{ display: "flex", gap: "0.25rem" }}>
                {workspace && (
                  <>
                    <button
                      onClick={() => handleTriggerCreate(workspace.path, "file")}
                      style={iconButtonStyle}
                      title="New File at Root..."
                    >
                      📄+
                    </button>
                    <button
                      onClick={() => handleTriggerCreate(workspace.path, "directory")}
                      style={iconButtonStyle}
                      title="New Folder at Root..."
                    >
                      📁+
                    </button>
                  </>
                )}
                <button
                  onClick={loadFiles}
                  disabled={isRefreshing}
                  style={iconButtonStyle}
                  title="Refresh tree"
                >
                  🔄
                </button>
              </div>
            )}
            {activeTab === "git" && (
              <button
                onClick={loadGitStatus}
                disabled={gitLoading}
                style={iconButtonStyle}
                title="Refresh git status"
              >
                🔄
              </button>
            )}
          </div>

          <div style={sidebarContentStyle}>
            {activeTab === "explorer" && (
              <>
                {/* Workspace Root Section */}
                {workspace ? (
                  <div style={{ marginBottom: "1.5rem" }}>
                    <div style={treeSectionHeaderStyle}>
                      💼 {workspace.name} <span style={pathBadgeStyle} title={workspace.path}>root</span>
                    </div>
                    <div style={{ padding: "0.25rem 0.5rem" }}>
                      {workspace.tree.map((node) => (
                        <FileItemNode 
                          key={node.path} 
                          node={node} 
                          onSelect={handleOpenFile} 
                          onCreate={handleTriggerCreate}
                          onRename={handleTriggerRename}
                          onDelete={handleTriggerDelete}
                          isReadOnly={false}
                        />
                      ))}
                    </div>
                  </div>
                ) : (
                  <div style={{ padding: "1rem", color: "var(--muted)", fontSize: "0.8rem" }}>
                    Scanning Workspace directory...
                  </div>
                )}

                {/* Scoped Directories Section */}
                {scoped.length > 0 && (
                  <div>
                    <div style={{ ...treeSectionHeaderStyle, borderTop: "1px solid var(--border)", paddingTop: "1rem" }}>
                      🔍 Scoped Folders ({scoped.length})
                    </div>
                    {scoped.map((scope) => (
                      <div key={scope.path} style={{ marginTop: "0.75rem", padding: "0 0.5rem" }}>
                        <div style={{ ...itemHeaderStyle, display: "flex", gap: "0.25rem", color: "#a855f7", fontSize: "0.75rem", fontWeight: 700, padding: "0.25rem" }} title={scope.path}>
                          🔗 {scope.name}/
                        </div>
                        <div style={{ paddingLeft: "0.25rem" }}>
                          {scope.tree.map((node) => (
                            <FileItemNode 
                              key={node.path} 
                              node={node} 
                              onSelect={handleOpenFile} 
                              onCreate={handleTriggerCreate}
                              onRename={handleTriggerRename}
                              onDelete={handleTriggerDelete}
                              isReadOnly={true}
                            />
                          ))}
                        </div>
                      </div>
                    ))}
                  </div>
                )}
              </>
            )}

            {activeTab === "git" && (
              <div style={{ padding: "0.5rem 1rem" }}>
                <div style={{ fontSize: "0.75rem", fontWeight: 700, textTransform: "uppercase", color: "var(--muted)", marginBottom: "0.5rem" }}>
                  Changes
                </div>
                {!isGitRepo ? (
                  <div style={{ color: "var(--muted)", fontSize: "0.75rem", fontStyle: "italic" }}>
                    Not a git repository.
                  </div>
                ) : gitFiles.length === 0 ? (
                  <div style={{ color: "var(--success)", fontSize: "0.75rem", padding: "0.5rem 0" }}>
                    ✔ Workspace clean.
                  </div>
                ) : (
                  <div style={{ display: "flex", flexDirection: "column", gap: "0.25rem" }}>
                    {gitFiles.map((file) => {
                      let badgeColor = "#eab308";
                      if (file.status === "??") badgeColor = "#10b981";
                      if (file.status === "A") badgeColor = "#10b981";
                      if (file.status === "D") badgeColor = "#ef4444";
                      return (
                        <div
                          key={file.relativePath}
                          onClick={async () => {
                            try {
                              const res = await fetch(`/api/git?action=diff&file=${encodeURIComponent(file.relativePath)}&root=${encodeURIComponent(workspaceRoot)}`);
                              if (res.ok) {
                                const data = await res.json();
                                if (data.success) {
                                  const diffPath = `diff:${file.relativePath}`;
                                  if (!openFiles.some(f => f.path === diffPath)) {
                                    setOpenFiles(prev => [
                                      ...prev,
                                      {
                                        name: `Diff: ${file.name}`,
                                        path: diffPath,
                                        content: data.diff,
                                        isModified: false
                                      }
                                    ]);
                                  }
                                  setActiveFilePath(diffPath);
                                }
                              }
                            } catch (e) {
                              console.error(e);
                            }
                          }}
                          style={{
                            display: "flex",
                            alignItems: "center",
                            justifyContent: "space-between",
                            padding: "0.35rem 0.5rem",
                            borderRadius: "4px",
                            backgroundColor: "rgba(255,255,255,0.02)",
                            cursor: "pointer",
                            fontSize: "0.75rem",
                            fontFamily: "var(--font-mono)",
                          }}
                          onMouseEnter={(e) => e.currentTarget.style.backgroundColor = "rgba(255,255,255,0.06)"}
                          onMouseLeave={(e) => e.currentTarget.style.backgroundColor = "rgba(255,255,255,0.02)"}
                        >
                          <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", flex: 1 }} title={file.relativePath}>
                            {file.name}
                          </span>
                          <span style={{ fontSize: "0.6rem", padding: "0.1rem 0.3rem", borderRadius: "3px", backgroundColor: badgeColor + "22", color: badgeColor, fontWeight: 700 }}>
                            {file.status}
                          </span>
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
            )}

            {activeTab === "analytics" && (
              <div style={{ padding: "0.5rem 1rem", display: "flex", flexDirection: "column", gap: "1.25rem" }}>
                <div>
                  <div style={{ fontSize: "0.75rem", fontWeight: 700, textTransform: "uppercase", color: "var(--muted)", marginBottom: "0.5rem" }}>
                    Token Usage
                  </div>
                  <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "0.5rem" }}>
                    <div style={analyticsCardStyle}>
                      <div style={analyticsCardLabelStyle}>Input</div>
                      <div style={analyticsCardValueStyle}>{(sessionStatus?.tokenUsage?.input ?? 0).toLocaleString()}</div>
                    </div>
                    <div style={analyticsCardStyle}>
                      <div style={analyticsCardLabelStyle}>Output</div>
                      <div style={analyticsCardValueStyle}>{(sessionStatus?.tokenUsage?.output ?? 0).toLocaleString()}</div>
                    </div>
                    <div style={{ ...analyticsCardStyle, gridColumn: "span 2" }}>
                      <div style={analyticsCardLabelStyle}>Cost</div>
                      <div style={{ ...analyticsCardValueStyle, color: "#10b981", fontSize: "1.25rem" }}>
                        ${(sessionStatus?.tokenUsage?.cost ?? 0).toFixed(4)}
                      </div>
                    </div>
                  </div>
                </div>

                <div>
                  <div style={{ fontSize: "0.75rem", fontWeight: 700, textTransform: "uppercase", color: "var(--muted)", marginBottom: "0.5rem" }}>
                    Resource Telemetry
                  </div>
                  <div style={{ display: "flex", flexDirection: "column", gap: "0.75rem" }}>
                    <div>
                      <div style={{ display: "flex", justifyContent: "space-between", fontSize: "0.7rem", marginBottom: "0.25rem" }}>
                        <span>CPU Usage</span>
                        <span style={{ fontWeight: 600, color: "var(--primary)" }}>{stats?.cpu ?? "0.0%"}</span>
                      </div>
                      <div style={gaugeOuterStyle}>
                        <div style={{ ...gaugeInnerStyle, width: stats?.cpu || "0%", backgroundColor: "var(--primary)" }}></div>
                      </div>
                    </div>
                    <div>
                      <div style={{ display: "flex", justifyContent: "space-between", fontSize: "0.7rem", marginBottom: "0.25rem" }}>
                        <span>Memory Usage</span>
                        <span style={{ fontWeight: 600, color: "#eab308" }}>{stats?.memory ?? "0.0MiB"}</span>
                      </div>
                      <div style={gaugeOuterStyle}>
                        <div style={{ ...gaugeInnerStyle, width: stats?.memoryPercent || "0%", backgroundColor: "#eab308" }}></div>
                      </div>
                    </div>
                    <div style={{ fontSize: "0.6rem", color: "var(--muted)", marginTop: "0.25rem", fontStyle: "italic" }}>
                      {stats?.type?.includes("docker") ? "🐳 Docker container statistics" : "💻 Local process statistics"}
                    </div>
                  </div>
                </div>
              </div>
            )}

            {activeTab === "auditor" && (
              <div style={{ padding: "0.5rem 1rem", display: "flex", flexDirection: "column", gap: "1rem", height: "100%" }}>
                <div style={{ display: "flex", gap: "0.25rem" }}>
                  <input
                    type="text"
                    placeholder="Search logs..."
                    value={logSearchQuery}
                    onChange={(e) => setLogSearchQuery(e.target.value)}
                    style={{
                      flex: 1,
                      backgroundColor: "#05070a",
                      border: "1px solid var(--border)",
                      borderRadius: "4px",
                      padding: "0.25rem 0.5rem",
                      color: "#ffffff",
                      fontSize: "0.75rem",
                      outline: "none"
                    }}
                  />
                  <button
                    onClick={handleExportLog}
                    style={{
                      backgroundColor: "rgba(59, 130, 246, 0.15)",
                      border: "1px solid #3b82f6",
                      color: "#3b82f6",
                      padding: "0.25rem 0.5rem",
                      borderRadius: "4px",
                      fontSize: "0.7rem",
                      fontWeight: 600,
                      cursor: "pointer"
                    }}
                  >
                    Export
                  </button>
                </div>

                <div style={{
                  height: "220px",
                  overflowY: "auto",
                  backgroundColor: "#05070a",
                  border: "1px solid var(--border)",
                  borderRadius: "6px",
                  padding: "0.5rem",
                  fontFamily: "var(--font-mono)",
                  fontSize: "0.7rem",
                  lineHeight: "1.4",
                  whiteSpace: "pre-wrap",
                  color: "#cbd5e1"
                }}>
                  {(() => {
                    if (!sessionStatus?.logs || sessionStatus.logs.length === 0) {
                      return <div style={{ color: "var(--muted)", fontStyle: "italic", textAlign: "center" }}>No logs captured.</div>;
                    }
                    const fullLogString = sessionStatus.logs.join("");
                    const cleanLogs = fullLogString.replace(/\x1b\[[0-9;]*m/g, "");
                    const lines = cleanLogs.split(/\r?\n/);
                    const filteredLines = logSearchQuery.trim()
                      ? lines.filter((line: string) => line.toLowerCase().includes(logSearchQuery.toLowerCase()))
                      : lines;
                    if (filteredLines.length === 0) {
                      return <div style={{ color: "var(--muted)", fontStyle: "italic", textAlign: "center" }}>No matches.</div>;
                    }
                    return filteredLines.map((line: string, i: number) => {
                      if (!logSearchQuery.trim()) return <div key={i}>{line}</div>;
                      const parts = line.split(new RegExp(`(${logSearchQuery})`, "gi"));
                      return (
                        <div key={i}>
                          {parts.map((part: string, j: number) => 
                            part.toLowerCase() === logSearchQuery.toLowerCase()
                              ? <span key={j} style={{ backgroundColor: "#eab308", color: "#000000", fontWeight: 600 }}>{part}</span>
                              : part
                          )}
                        </div>
                      );
                    });
                  })()}
                </div>

                <div style={{ borderTop: "1px solid var(--border)", paddingTop: "0.75rem" }}>
                  <div style={{ fontSize: "0.75rem", fontWeight: 700, color: "var(--muted)", marginBottom: "0.5rem" }}>
                    Custom Buttons
                  </div>
                  <div style={{ display: "flex", flexDirection: "column", gap: "0.35rem" }}>
                    <input
                      type="text"
                      placeholder="Button Name (e.g. /undo)"
                      value={newCmdName}
                      onChange={(e) => setNewCmdName(e.target.value)}
                      style={{
                        backgroundColor: "#05070a",
                        border: "1px solid var(--border)",
                        borderRadius: "4px",
                        padding: "0.25rem 0.5rem",
                        color: "#ffffff",
                        fontSize: "0.7rem",
                        outline: "none"
                      }}
                    />
                    <input
                      type="text"
                      placeholder="Injection Command"
                      value={newCmdStr}
                      onChange={(e) => setNewCmdStr(e.target.value)}
                      style={{
                        backgroundColor: "#05070a",
                        border: "1px solid var(--border)",
                        borderRadius: "4px",
                        padding: "0.25rem 0.5rem",
                        color: "#ffffff",
                        fontSize: "0.7rem",
                        outline: "none"
                      }}
                    />
                    <button
                      onClick={handleAddCommand}
                      style={{
                        backgroundColor: "rgba(168, 85, 247, 0.15)",
                        border: "1px solid #a855f7",
                        color: "#c084fc",
                        padding: "0.3rem",
                        borderRadius: "4px",
                        fontSize: "0.7rem",
                        fontWeight: 600,
                        cursor: "pointer"
                      }}
                    >
                      + Add Button
                    </button>
                    {customCommands.length > 0 && (
                      <div style={{ marginTop: "0.25rem", maxHeight: "60px", overflowY: "auto" }}>
                        {customCommands.map((cmd, idx) => (
                          <div key={idx} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", fontSize: "0.65rem", backgroundColor: "rgba(255,255,255,0.02)", padding: "0.1rem 0.25rem", borderRadius: "3px", marginTop: "0.15rem" }}>
                            <span style={{ color: "#c084fc" }}>{cmd.name}</span>
                            <span onClick={() => handleDeleteCommand(idx)} style={{ color: "var(--danger)", cursor: "pointer" }}>✖</span>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Editor & Console Split View */}
      <div style={mainContentAreaStyle}>
        {/* Session Tab Bar Switcher */}
        <div style={sessionTabBarStyle}>
          <div style={{ display: "flex", gap: "0.25rem", overflowX: "auto" }}>
            {sessions.map((s) => {
              const isActive = s.id === sessionId;
              const statusColor = s.status === "running" ? "#10b981" : "rgba(255,255,255,0.2)";
              return (
                <div
                  key={s.id}
                  onClick={() => {
                    // Close split view if switching to that session
                    if (splitSessionId === s.id) {
                      setSplitSessionId(null);
                    }
                    onSwitchSession(s.id);
                  }}
                  style={{
                    ...sessionTabItemStyle,
                    backgroundColor: isActive ? "#0b101b" : "rgba(8,12,20,0.6)",
                    borderColor: isActive ? "var(--border-focus)" : "var(--border)",
                    color: isActive ? "var(--foreground)" : "var(--muted)",
                  }}
                >
                  <span 
                    style={{ 
                      width: "6px", 
                      height: "6px", 
                      borderRadius: "50%", 
                      backgroundColor: statusColor,
                      display: "inline-block",
                    }}
                  />
                  <span style={{ fontSize: "0.75rem", fontWeight: isActive ? 600 : 500 }}>
                    {s.name}
                  </span>
                  <span style={{ fontSize: "0.6rem", color: "var(--muted)", backgroundColor: "rgba(255,255,255,0.05)", padding: "1px 4px", borderRadius: "3px" }}>
                    {s.type.replace("claude-", "").replace("aider-", "")}
                  </span>
                </div>
              );
            })}
          </div>
        </div>

        {/* Editor Panel (top half) */}
        <div style={editorPanelStyle}>
          {/* Tabs header */}
          <div style={tabHeaderStyle}>
            <div style={tabsWrapperStyle}>
              {openFiles.map((file) => (
                <div
                  key={file.path}
                  style={{
                    ...tabItemStyle,
                    backgroundColor: activeFilePath === file.path ? "#0b101b" : "rgba(8,12,20,0.4)",
                    borderColor: activeFilePath === file.path ? "var(--border-focus)" : "transparent",
                    color: activeFilePath === file.path ? "var(--foreground)" : "var(--muted)",
                  }}
                  onClick={() => setActiveFilePath(file.path)}
                >
                  <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                    {file.name} {file.isModified && <span style={modifiedDotStyle}>●</span>}
                  </span>
                  <span
                    onClick={(e) => {
                      e.stopPropagation();
                      handleCloseFile(file.path);
                    }}
                    style={closeTabStyle}
                  >
                    ✖
                  </span>
                </div>
              ))}
            </div>

            {activeFile && !activeFile.path.startsWith("diff:") && (
              <button
                onClick={handleSaveFile}
                disabled={!activeFile.isModified}
                style={{
                  ...saveButtonStyle,
                  opacity: activeFile.isModified ? 1 : 0.5,
                  cursor: activeFile.isModified ? "pointer" : "not-allowed",
                }}
              >
                💾 Save (Ctrl+S)
              </button>
            )}
          </div>

          {/* Editor contents */}
          <div style={editorWorkspaceStyle}>
            {activeFile ? (
              activeFile.path.startsWith("diff:") ? (
                <div style={{ fontFamily: "var(--font-mono)", fontSize: "0.8rem", padding: "1rem", overflow: "auto", height: "100%", backgroundColor: "#0b101b", lineHeight: 1.5 }}>
                  {activeFile.content.split("\n").map((line, i) => {
                    let color = "#e2e8f0";
                    let bg = "transparent";
                    if (line.startsWith("+")) {
                      color = "#4ade80";
                      bg = "rgba(74, 222, 128, 0.08)";
                    } else if (line.startsWith("-")) {
                      color = "#f87171";
                      bg = "rgba(248, 113, 113, 0.08)";
                    } else if (line.startsWith("@@")) {
                      color = "#60a5fa";
                      bg = "rgba(96, 165, 250, 0.05)";
                    }
                    return (
                      <div key={i} style={{ color, backgroundColor: bg, whiteSpace: "pre-wrap", padding: "0.1rem 0.5rem" }}>
                        {line}
                      </div>
                    );
                  })}
                </div>
              ) : (
                <textarea
                  value={activeFile.content}
                  onChange={(e) => handleContentChange(e.target.value)}
                  style={textareaStyle}
                  spellCheck={false}
                />
              )
            ) : (
              <div style={emptyEditorStateStyle}>
                <div style={{ fontSize: "2rem", marginBottom: "1rem" }}>💻</div>
                <h4 style={{ margin: 0, fontWeight: 600 }}>NeuralLoom Workspace Editor</h4>
                <p style={{ margin: "0.5rem 0 0 0", color: "var(--muted)", fontSize: "0.8rem" }}>
                  Select files from the left explorer panel to view and edit. Use Ctrl+S to save changes.
                </p>
                <p style={{ margin: "0.5rem 0 0 0", color: "var(--muted)", fontSize: "0.75rem", fontStyle: "italic" }}>
                  Press <kbd style={{ background: "rgba(255,255,255,0.1)", padding: "2px 4px", borderRadius: "3px" }}>Ctrl+P</kbd> to search files.
                </p>
              </div>
            )}
          </div>
        </div>

        {/* Console / PTY Bridge Panel (bottom half) */}
        <div style={terminalPanelStyle}>
          {/* Dashboard control headers injected above xterm */}
          <div style={terminalHeaderStyle}>
            <span style={{ display: "flex", alignItems: "center", gap: "0.5rem", fontWeight: 600, fontSize: "0.8rem" }}>
              🖥️ Session Console Bridge {splitSessionId && `(Split View Active)`}
            </span>
            
            <div style={{ display: "flex", gap: "0.5rem", alignItems: "center" }}>
              {/* Split dropdown controller */}
              <select
                onChange={(e) => {
                  const val = e.target.value;
                  setSplitSessionId(val ? val : null);
                }}
                value={splitSessionId || ""}
                style={{
                  backgroundColor: "#080c14",
                  border: "1px solid var(--border)",
                  borderRadius: "4px",
                  padding: "0.2rem 0.5rem",
                  color: "var(--foreground)",
                  fontSize: "0.7rem",
                  outline: "none",
                  cursor: "pointer",
                }}
              >
                <option value="">🖥️ Single Terminal</option>
                {sessions
                  .filter(s => s.id !== sessionId && s.status === 'running')
                  .map(s => (
                    <option key={s.id} value={s.id}>🖥️|🖥️ Split: {s.name}</option>
                  ))
                }
              </select>

              <button
                onClick={async () => {
                  await fetch("/api/sessions/inject", {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify({ id: sessionId, command: "/ccc" }),
                  });
                }}
                style={contextButtonStyle}
              >
                🚀 Mount Context (/ccc)
              </button>
              <button
                onClick={async () => {
                  await fetch("/api/sessions/inject", {
                    method: "POST",
                    headers: { "Content-Type": "application/json" },
                    body: JSON.stringify({ id: sessionId, command: "/ccp" }),
                  });
                }}
                style={promptButtonStyle}
              >
                ⚡ Trigger Prompt (/ccp)
              </button>
            </div>
          </div>

          {/* Quick command buttons toolbar */}
          <div style={quickCommandToolbarStyle}>
            <span style={{ fontSize: "0.7rem", color: "var(--muted)", textTransform: "uppercase", letterSpacing: "0.05em", fontWeight: 700 }}>
              Quick Commands:
            </span>
            <div style={{ display: "flex", gap: "0.35rem", flexWrap: "wrap", alignItems: "center" }}>
              {isAider ? (
                <>
                  <button onClick={() => triggerInject("/undo")} style={quickCmdBtnStyle} title="Aider: undo last commit">/undo</button>
                  <button onClick={() => triggerInject("/diff")} style={quickCmdBtnStyle} title="Aider: show git diff">/diff</button>
                  <button onClick={() => triggerInject("/commit")} style={quickCmdBtnStyle} title="Aider: commit edits">/commit</button>
                  <button onClick={() => triggerInject("/test")} style={quickCmdBtnStyle} title="Aider: run tests">/test</button>
                  <button onClick={() => triggerInject("/clear")} style={quickCmdBtnStyle} title="Clear terminal screen">/clear</button>
                </>
              ) : (
                <>
                  <button onClick={() => triggerInject("/compact")} style={quickCmdBtnStyle} title="Claude Code: compact history">/compact</button>
                  <button onClick={() => triggerInject("/history")} style={quickCmdBtnStyle} title="Claude Code: view history">/history</button>
                  <button onClick={() => triggerInject("/reset")} style={quickCmdBtnStyle} title="Claude Code: reset conversation">/reset</button>
                  <button onClick={() => triggerInject("/help")} style={quickCmdBtnStyle} title="Claude Code: show help">/help</button>
                </>
              )}

              {/* Custom buttons */}
              {customCommands.map((cmd, i) => (
                <button
                  key={i}
                  onClick={() => triggerInject(cmd.command)}
                  style={{ ...quickCmdBtnStyle, borderColor: "rgba(168, 85, 247, 0.4)", color: "#c084fc" }}
                  title={`Inject command: ${cmd.command}`}
                >
                  {cmd.name}
                </button>
              ))}
            </div>
          </div>

          <div style={{ ...terminalConsoleWrapperStyle, display: "flex", width: "100%", height: "100%" }}>
            <div style={{ flex: 1, height: "100%", borderRight: splitSessionId ? "1px solid var(--border)" : "none", overflow: "hidden" }}>
              <TerminalConsole sessionId={sessionId} height="100%" />
            </div>
            {splitSessionId && (
              <div style={{ flex: 1, height: "100%", overflow: "hidden", display: "flex", flexDirection: "column" }}>
                {/* Header for split console */}
                <div style={{ padding: "0.25rem 0.5rem", backgroundColor: "#030406", fontSize: "0.7rem", borderBottom: "1px solid var(--border)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                  <span style={{ color: "#a855f7", fontWeight: 600 }}>🔗 Focused PTY Connection: {sessions.find(s => s.id === splitSessionId)?.name}</span>
                  <button 
                    onClick={() => setSplitSessionId(null)}
                    style={{ background: "none", border: "none", color: "var(--danger)", cursor: "pointer", fontSize: "0.7rem" }}
                  >
                    Close Split ✖
                  </button>
                </div>
                <div style={{ flex: 1, overflow: "hidden" }}>
                  <TerminalConsole sessionId={splitSessionId} height="100%" />
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Overlay Modal for File Actions */}
      {dialog.type && (
        <div style={modalOverlayStyle}>
          <div style={modalContentStyle}>
            <h3 style={{ margin: "0 0 1rem 0", fontSize: "1rem", fontWeight: 600 }}>
              {dialog.type === "create-file" && "Create New File"}
              {dialog.type === "create-folder" && "Create New Folder"}
              {dialog.type === "rename" && "Rename Item"}
              {dialog.type === "delete" && "Confirm Deletion"}
            </h3>
            
            {dialog.error && (
              <div style={{ color: "var(--danger)", fontSize: "0.8rem", marginBottom: "1rem" }}>
                ⚠️ {dialog.error}
              </div>
            )}

            {dialog.type !== "delete" ? (
              <form onSubmit={handleDialogSubmit}>
                <div style={{ marginBottom: "0.5rem", fontSize: "0.75rem", color: "var(--muted)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }} title={dialog.targetPath || ""}>
                  Target: {dialog.targetPath}
                </div>
                <input
                  type="text"
                  value={dialog.inputValue}
                  onChange={(e) => setDialog({ ...dialog, inputValue: e.target.value })}
                  style={modalInputStyle}
                  autoFocus
                  placeholder={
                    dialog.type === "rename" ? "Enter new name" : "Enter name"
                  }
                />
                <div style={modalActionsStyle}>
                  <button
                    type="button"
                    onClick={() => setDialog({ type: null, targetPath: null, inputValue: "", error: null })}
                    style={modalCancelBtnStyle}
                  >
                    Cancel
                  </button>
                  <button type="submit" style={modalConfirmBtnStyle}>
                    Submit
                  </button>
                </div>
              </form>
            ) : (
              <div>
                <div style={{ fontSize: "0.85rem", marginBottom: "1.5rem", color: "var(--muted)", overflowWrap: "break-word" }}>
                  Are you sure you want to delete this item? This action is permanent.
                  <div style={{ marginTop: "0.5rem", color: "#e2e8f0", fontFamily: "var(--font-mono)", fontSize: "0.75rem", background: "rgba(255,255,255,0.05)", padding: "0.5rem", borderRadius: "4px" }}>
                    {dialog.targetPath}
                  </div>
                </div>
                <div style={modalActionsStyle}>
                  <button
                    type="button"
                    onClick={() => setDialog({ type: null, targetPath: null, inputValue: "", error: null })}
                    style={modalCancelBtnStyle}
                  >
                    Cancel
                  </button>
                  <button
                    onClick={() => handleDialogSubmit()}
                    style={{ ...modalConfirmBtnStyle, backgroundColor: "var(--danger)" }}
                  >
                    Delete Permanently
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Fuzzy File Finder Modal */}
      {searchOpen && (
        <div style={searchOverlayStyle} onClick={() => setSearchOpen(false)}>
          <div style={searchContentStyle} onClick={(e) => e.stopPropagation()}>
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => {
                setSearchQuery(e.target.value);
                setSearchSelectedIndex(0);
              }}
              onKeyDown={handleSearchKeyDown}
              placeholder="Search files by name or path..."
              style={searchInputStyle}
              autoFocus
            />
            <div style={searchResultsListStyle}>
              {filteredFiles.length > 0 ? (
                filteredFiles.map((file, idx) => (
                  <div
                    key={file.path}
                    onClick={() => {
                      handleOpenFile(file.path);
                      setSearchOpen(false);
                    }}
                    style={{
                      ...searchResultItemStyle,
                      backgroundColor: idx === searchSelectedIndex ? "rgba(168, 85, 247, 0.15)" : "transparent",
                      borderLeft: idx === searchSelectedIndex ? "3px solid var(--primary)" : "3px solid transparent",
                    }}
                  >
                    <span style={{ fontSize: "0.85rem", fontWeight: 600 }}>{file.name}</span>
                    <span style={{ fontSize: "0.7rem", color: "var(--muted)", marginLeft: "0.5rem", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
                      {file.relativePath}
                    </span>
                  </div>
                ))
              ) : (
                <div style={{ padding: "0.75rem 1rem", color: "var(--muted)", fontSize: "0.8rem", textAlign: "center" }}>
                  No matching files found
                </div>
              )}
            </div>
            <div style={{ padding: "0.5rem 1rem", borderTop: "1px solid var(--border)", fontSize: "0.65rem", color: "var(--muted)", textAlign: "right" }}>
              Use ↑↓ to navigate, Enter to select, Esc to close
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// Styling definitions to create premium dark-mode HSL style
const ideContainerStyle: React.CSSProperties = {
  display: "flex",
  width: "100%",
  height: "calc(100vh - 120px)",
  backgroundColor: "#05070a",
  border: "1px solid var(--border)",
  borderRadius: "12px",
  overflow: "hidden",
  boxShadow: "0 20px 25px -5px rgba(0, 0, 0, 0.6)",
};

const activityBarStyle: React.CSSProperties = {
  width: "50px",
  backgroundColor: "#030406",
  borderRight: "1px solid var(--border)",
  display: "flex",
  flexDirection: "column",
  justifyContent: "space-between",
  alignItems: "center",
  padding: "0.75rem 0",
};

const topIconsStyle: React.CSSProperties = {
  display: "flex",
  flexDirection: "column",
  width: "100%",
  gap: "0.5rem",
};

const sidebarIconStyle: React.CSSProperties = {
  width: "100%",
  height: "45px",
  display: "flex",
  alignItems: "center",
  justifyContent: "center",
  cursor: "pointer",
  fontSize: "1.25rem",
  transition: "all 0.15s ease",
};

const sidebarPanelStyle: React.CSSProperties = {
  width: "260px",
  backgroundColor: "#080c14",
  borderRight: "1px solid var(--border)",
  display: "flex",
  flexDirection: "column",
  overflow: "hidden",
};

const sidebarHeaderStyle: React.CSSProperties = {
  padding: "0.75rem 1rem",
  borderBottom: "1px solid var(--border)",
  display: "flex",
  alignItems: "center",
  justifyContent: "space-between",
  background: "rgba(255,255,255,0.02)",
};


const sidebarContentStyle: React.CSSProperties = {
  flex: 1,
  overflowY: "auto",
  padding: "0.75rem 0",
};

const treeSectionHeaderStyle: React.CSSProperties = {
  padding: "0.25rem 1rem",
  fontSize: "0.75rem",
  fontWeight: 700,
  color: "var(--muted)",
  display: "flex",
  alignItems: "center",
  justifyContent: "space-between",
  textTransform: "uppercase",
  letterSpacing: "0.05em",
};

const pathBadgeStyle: React.CSSProperties = {
  fontSize: "0.6rem",
  backgroundColor: "rgba(59, 130, 246, 0.1)",
  color: "#3b82f6",
  padding: "0.1rem 0.3rem",
  borderRadius: "3px",
  textTransform: "none",
  letterSpacing: "normal",
};

const itemHeaderStyle: React.CSSProperties = {
  fontSize: "0.75rem",
  fontWeight: 600,
  color: "var(--foreground)",
};

const mainContentAreaStyle: React.CSSProperties = {
  flex: 1,
  display: "flex",
  flexDirection: "column",
  overflow: "hidden",
  backgroundColor: "#0b101b",
};

const editorPanelStyle: React.CSSProperties = {
  flex: 1,
  display: "flex",
  flexDirection: "column",
  borderBottom: "1px solid var(--border)",
  overflow: "hidden",
};

const tabHeaderStyle: React.CSSProperties = {
  height: "35px",
  backgroundColor: "#05070a",
  borderBottom: "1px solid var(--border)",
  display: "flex",
  alignItems: "center",
  justifyContent: "space-between",
  paddingRight: "0.75rem",
};

const tabsWrapperStyle: React.CSSProperties = {
  display: "flex",
  height: "100%",
  overflowX: "auto",
};

const tabItemStyle: React.CSSProperties = {
  padding: "0 1rem",
  height: "100%",
  display: "flex",
  alignItems: "center",
  gap: "0.75rem",
  fontSize: "0.75rem",
  borderRight: "1px solid var(--border)",
  borderBottom: "2px solid transparent",
  cursor: "pointer",
  transition: "all 0.15s ease",
  maxWidth: "150px",
};

const closeTabStyle: React.CSSProperties = {
  fontSize: "0.65rem",
  color: "var(--muted)",
  cursor: "pointer",
  padding: "2px",
};

const modifiedDotStyle: React.CSSProperties = {
  color: "var(--primary)",
  fontSize: "0.65rem",
  marginLeft: "2px",
};

const saveButtonStyle: React.CSSProperties = {
  padding: "0.25rem 0.5rem",
  borderRadius: "4px",
  border: "1px solid var(--border-focus)",
  backgroundColor: "rgba(16, 185, 129, 0.15)",
  color: "var(--success)",
  fontSize: "0.7rem",
  fontWeight: 600,
};

const editorWorkspaceStyle: React.CSSProperties = {
  flex: 1,
  position: "relative",
  overflow: "hidden",
};

const textareaStyle: React.CSSProperties = {
  width: "100%",
  height: "100%",
  backgroundColor: "#0b101b",
  border: "none",
  outline: "none",
  color: "#e2e8f0",
  fontFamily: "var(--font-mono), monospace",
  fontSize: "0.85rem",
  padding: "1rem",
  resize: "none",
  lineHeight: 1.5,
};

const emptyEditorStateStyle: React.CSSProperties = {
  display: "flex",
  flexDirection: "column",
  alignItems: "center",
  justifyContent: "center",
  height: "100%",
  color: "var(--muted)",
  textAlign: "center",
  padding: "2rem",
};

const terminalPanelStyle: React.CSSProperties = {
  height: "360px",
  backgroundColor: "#05070a",
  display: "flex",
  flexDirection: "column",
  overflow: "hidden",
};

const terminalHeaderStyle: React.CSSProperties = {
  padding: "0.5rem 1rem",
  borderBottom: "1px solid var(--border)",
  display: "flex",
  alignItems: "center",
  justifyContent: "space-between",
  backgroundColor: "rgba(255,255,255,0.01)",
};

const contextButtonStyle: React.CSSProperties = {
  padding: "0.3rem 0.6rem",
  borderRadius: "4px",
  border: "1px solid var(--primary)",
  backgroundColor: "transparent",
  color: "var(--primary)",
  fontSize: "0.7rem",
  fontWeight: 600,
  cursor: "pointer",
};

const promptButtonStyle: React.CSSProperties = {
  padding: "0.3rem 0.6rem",
  borderRadius: "4px",
  border: "1px solid var(--success)",
  backgroundColor: "transparent",
  color: "var(--success)",
  fontSize: "0.7rem",
  fontWeight: 600,
  cursor: "pointer",
};

const terminalConsoleWrapperStyle: React.CSSProperties = {
  flex: 1,
  overflow: "hidden",
};

interface FileItemNodeProps {
  node: FileNode;
  onSelect: (p: string) => void;
  onCreate: (parentPath: string, type: "file" | "directory") => void;
  onRename: (path: string) => void;
  onDelete: (path: string) => void;
  isReadOnly?: boolean;
}

// Define outside IdeLayout to prevent component re-creation and auto-collapsing
function FileItemNode({ 
  node, 
  onSelect,
  onCreate,
  onRename,
  onDelete,
  isReadOnly = false
}: FileItemNodeProps) {
  const [expanded, setExpanded] = useState(false);
  const [hovered, setHovered] = useState(false);

  const isFolder = node.type === "directory";
  
  const itemStyle = {
    padding: "0.25rem 0.5rem",
    display: "flex",
    alignItems: "center",
    justifyContent: "space-between",
    fontSize: "0.8rem",
    fontFamily: "var(--font-mono), monospace",
    cursor: "pointer",
    color: "var(--foreground)",
    borderRadius: "4px",
    transition: "background 0.1s ease",
    userSelect: "none" as const,
    backgroundColor: hovered ? "rgba(255, 255, 255, 0.05)" : "transparent",
    minWidth: 0,
    width: "100%",
  };

  const textContainerStyle = {
    display: "flex",
    alignItems: "center",
    gap: "0.375rem",
    flex: 1,
    minWidth: 0,
    overflow: "hidden",
    textOverflow: "ellipsis",
    whiteSpace: "nowrap" as const,
  };

  const actionsStyle = {
    display: hovered ? "flex" : "none",
    alignItems: "center",
    gap: "0.25rem",
    paddingLeft: "0.5rem",
    flexShrink: 0,
  };

  const actionBtnStyle = {
    background: "none",
    border: "none",
    padding: "2px 4px",
    cursor: "pointer",
    fontSize: "0.75rem",
    color: "var(--muted)",
    borderRadius: "3px",
    transition: "all 0.1s ease",
  };

  const handleAction = (e: React.MouseEvent, act: () => void) => {
    e.stopPropagation();
    act();
  };

  if (!isFolder) {
    return (
      <div
        onClick={() => onSelect(node.path)}
        style={itemStyle}
        onMouseEnter={() => setHovered(true)}
        onMouseLeave={() => setHovered(false)}
      >
        <div style={textContainerStyle}>
          <span style={{ color: "#3b82f6" }}>📄</span>
          <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{node.name}</span>
        </div>
        {!isReadOnly && (
          <div style={actionsStyle}>
            <button
              onClick={(e) => handleAction(e, () => onRename(node.path))}
              style={actionBtnStyle}
              title="Rename..."
              onMouseEnter={(e) => e.currentTarget.style.color = "var(--primary)"}
              onMouseLeave={(e) => e.currentTarget.style.color = "var(--muted)"}
            >
              ✏️
            </button>
            <button
              onClick={(e) => handleAction(e, () => onDelete(node.path))}
              style={actionBtnStyle}
              title="Delete File"
              onMouseEnter={(e) => e.currentTarget.style.color = "var(--danger)"}
              onMouseLeave={(e) => e.currentTarget.style.color = "var(--muted)"}
            >
              🗑️
            </button>
          </div>
        )}
      </div>
    );
  }

  return (
    <div>
      <div
        onClick={() => setExpanded(!expanded)}
        style={itemStyle}
        onMouseEnter={() => setHovered(true)}
        onMouseLeave={() => setHovered(false)}
      >
        <div style={textContainerStyle}>
          <span style={{ color: "#eab308" }}>{expanded ? "📂" : "📁"}</span>
          <span style={{ fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{node.name}</span>
        </div>
        {!isReadOnly && (
          <div style={actionsStyle}>
            <button
              onClick={(e) => handleAction(e, () => onCreate(node.path, "file"))}
              style={actionBtnStyle}
              title="New File inside..."
              onMouseEnter={(e) => e.currentTarget.style.color = "var(--success)"}
              onMouseLeave={(e) => e.currentTarget.style.color = "var(--muted)"}
            >
              📄+
            </button>
            <button
              onClick={(e) => handleAction(e, () => onCreate(node.path, "directory"))}
              style={actionBtnStyle}
              title="New Folder inside..."
              onMouseEnter={(e) => e.currentTarget.style.color = "var(--success)"}
              onMouseLeave={(e) => e.currentTarget.style.color = "var(--muted)"}
            >
              📁+
            </button>
            <button
              onClick={(e) => handleAction(e, () => onRename(node.path))}
              style={actionBtnStyle}
              title="Rename..."
              onMouseEnter={(e) => e.currentTarget.style.color = "var(--primary)"}
              onMouseLeave={(e) => e.currentTarget.style.color = "var(--muted)"}
            >
              ✏️
            </button>
            <button
              onClick={(e) => handleAction(e, () => onDelete(node.path))}
              style={actionBtnStyle}
              title="Delete Folder"
              onMouseEnter={(e) => e.currentTarget.style.color = "var(--danger)"}
              onMouseLeave={(e) => e.currentTarget.style.color = "var(--muted)"}
            >
              🗑️
            </button>
          </div>
        )}
      </div>
      {expanded && node.children && (
        <div style={{ paddingLeft: "10px", borderLeft: "1px solid rgba(255, 255, 255, 0.05)", marginLeft: "8px" }}>
          {node.children.map((child) => (
            <FileItemNode 
              key={child.path} 
              node={child} 
              onSelect={onSelect} 
              onCreate={onCreate}
              onRename={onRename}
              onDelete={onDelete}
              isReadOnly={isReadOnly}
            />
          ))}
        </div>
      )}
    </div>
  );
}

// Dialog operation styles
const modalOverlayStyle: React.CSSProperties = {
  position: "fixed",
  top: 0,
  left: 0,
  right: 0,
  bottom: 0,
  backgroundColor: "rgba(0,0,0,0.7)",
  display: "flex",
  alignItems: "center",
  justifyContent: "center",
  zIndex: 1000,
  backdropFilter: "blur(4px)",
};

const modalContentStyle: React.CSSProperties = {
  width: "420px",
  backgroundColor: "#080c14",
  border: "1px solid var(--border)",
  borderRadius: "12px",
  padding: "1.5rem",
  boxShadow: "0 20px 25px -5px rgba(0, 0, 0, 0.8)",
};

const modalInputStyle: React.CSSProperties = {
  width: "100%",
  backgroundColor: "#05070a",
  border: "1px solid var(--border)",
  borderRadius: "6px",
  padding: "0.5rem 0.75rem",
  color: "#e2e8f0",
  fontSize: "0.85rem",
  outline: "none",
  marginBottom: "1.5rem",
  fontFamily: "var(--font-mono), monospace",
};

const modalActionsStyle: React.CSSProperties = {
  display: "flex",
  justifyContent: "flex-end",
  gap: "0.75rem",
};

const modalCancelBtnStyle: React.CSSProperties = {
  backgroundColor: "transparent",
  border: "1px solid var(--border)",
  color: "var(--foreground)",
  padding: "0.5rem 1rem",
  borderRadius: "6px",
  fontSize: "0.8rem",
  fontWeight: 600,
  cursor: "pointer",
};

const modalConfirmBtnStyle: React.CSSProperties = {
  backgroundColor: "var(--primary)",
  border: "none",
  color: "#ffffff",
  padding: "0.5rem 1rem",
  borderRadius: "6px",
  fontSize: "0.8rem",
  fontWeight: 600,
  cursor: "pointer",
};

const iconButtonStyle: React.CSSProperties = {
  background: "none",
  border: "none",
  color: "var(--muted)",
  cursor: "pointer",
  fontSize: "0.8rem",
  padding: "4px",
  borderRadius: "3px",
  transition: "all 0.1s ease",
};

// Fuzzy search styles
const searchOverlayStyle: React.CSSProperties = {
  position: "fixed",
  top: 0,
  left: 0,
  right: 0,
  bottom: 0,
  backgroundColor: "rgba(0,0,0,0.5)",
  display: "flex",
  alignItems: "flex-start",
  justifyContent: "center",
  zIndex: 1100,
  paddingTop: "5vh",
  backdropFilter: "blur(2px)",
};

const searchContentStyle: React.CSSProperties = {
  width: "600px",
  backgroundColor: "#080c14",
  border: "1px solid var(--border)",
  borderRadius: "8px",
  boxShadow: "0 10px 25px -5px rgba(0, 0, 0, 0.8)",
  display: "flex",
  flexDirection: "column",
  overflow: "hidden",
};

const searchInputStyle: React.CSSProperties = {
  width: "100%",
  backgroundColor: "#05070a",
  border: "none",
  borderBottom: "1px solid var(--border)",
  padding: "0.75rem 1rem",
  color: "#e2e8f0",
  fontSize: "0.9rem",
  outline: "none",
  fontFamily: "var(--font-mono), monospace",
};

const searchResultsListStyle: React.CSSProperties = {
  maxHeight: "300px",
  overflowY: "auto",
  padding: "0.25rem 0",
};

const searchResultItemStyle: React.CSSProperties = {
  display: "flex",
  alignItems: "center",
  padding: "0.5rem 1rem",
  cursor: "pointer",
  transition: "all 0.1s ease",
  justifyContent: "space-between",
};

// Analytics Card & Resource Monitor styles
const analyticsCardStyle: React.CSSProperties = {
  backgroundColor: "rgba(255,255,255,0.02)",
  border: "1px solid var(--border)",
  borderRadius: "6px",
  padding: "0.5rem 0.75rem",
  display: "flex",
  flexDirection: "column",
  gap: "0.25rem",
};

const analyticsCardLabelStyle: React.CSSProperties = {
  fontSize: "0.6rem",
  color: "var(--muted)",
  textTransform: "uppercase",
};

const analyticsCardValueStyle: React.CSSProperties = {
  fontSize: "1.1rem",
  fontWeight: 700,
  fontFamily: "var(--font-mono)",
};

const gaugeOuterStyle: React.CSSProperties = {
  width: "100%",
  height: "6px",
  backgroundColor: "rgba(255,255,255,0.05)",
  borderRadius: "3px",
  overflow: "hidden",
};

const gaugeInnerStyle: React.CSSProperties = {
  height: "100%",
  borderRadius: "3px",
  transition: "width 0.5s ease-out",
};

const quickCommandToolbarStyle: React.CSSProperties = {
  padding: "0.35rem 1rem",
  borderBottom: "1px solid var(--border)",
  backgroundColor: "#030406",
  display: "flex",
  alignItems: "center",
  gap: "0.75rem",
  flexWrap: "nowrap",
  overflowX: "auto"
};

const quickCmdBtnStyle: React.CSSProperties = {
  padding: "0.15rem 0.45rem",
  borderRadius: "4px",
  border: "1px solid var(--border)",
  backgroundColor: "rgba(255,255,255,0.02)",
  color: "var(--muted)",
  fontSize: "0.7rem",
  fontFamily: "var(--font-mono)",
  fontWeight: 600,
  cursor: "pointer",
  transition: "all 0.1s ease",
};

const sessionTabBarStyle: React.CSSProperties = {
  backgroundColor: "#05070a",
  borderBottom: "1px solid var(--border)",
  padding: "0.25rem 0.75rem 0 0.75rem",
  display: "flex",
  alignItems: "center",
  justifyContent: "space-between",
};

const sessionTabItemStyle: React.CSSProperties = {
  padding: "0.35rem 0.75rem",
  borderRadius: "6px 6px 0 0",
  border: "1px solid var(--border)",
  borderBottom: "none",
  display: "flex",
  alignItems: "center",
  gap: "0.5rem",
  cursor: "pointer",
  transition: "all 0.15s ease",
};
