import { useState, useEffect, useRef, useContext, useCallback } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { socketClient } from '../lib/socket';
import { chatSessionApi, projectApi, providerApi, type ChatSession, type ChatTurn, ChatSessionMode, type AiProvider } from '../lib/api';
import { WorkspaceMode } from '../lib/types';
import WorkspaceModeIndicator from '../components/WorkspaceModeIndicator';
import FilesPanel from '../components/FilesPanel';
import LogPanel from '../components/LogPanel';
import ChatTurnComponent from '../components/ChatTurn';
import { AppContext } from '../App';

interface LogEntry {
  id: string;
  timestamp: Date;
  level: string;
  message: string;
}

interface StreamingState {
  currentMode: 'thinking' | 'responding' | null;
  thinkingContent: string;
  respondingContent: string;
  currentBlockIndex: number | null;
}

export default function ChatSessionView() {
  const { projectId, sessionId } = useParams<{ projectId: string; sessionId: string }>();
  const navigate = useNavigate();
  const appContext = useContext(AppContext);

  const [project, setProject] = useState<Project | null>(null);
  const [session, setSession] = useState<ChatSession | null>(null);
  const [turns, setTurns] = useState<ChatTurn[]>([]);
  const [promptInput, setPromptInput] = useState('');
  const [isProcessing, setIsProcessing] = useState(false);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [sessionLocked, setSessionLocked] = useState(true);
  const [workspaceMode, setWorkspaceMode] = useState<WorkspaceMode>(WorkspaceMode.Idle);
  const [isUpdatingMode, setIsUpdatingMode] = useState(false);
  const [isUpdatingProvider, setIsUpdatingProvider] = useState(false);
  const [isUpdatingModel, setIsUpdatingModel] = useState(false);
  const [logExpanded, setLogExpanded] = useState(false);
  const [logs, setLogs] = useState<LogEntry[]>([]);
  const [toast, setToast] = useState<string | null>(null);
  const [providers, setProviders] = useState<AiProvider[]>([]);
  const [selectedProviderId, setSelectedProviderId] = useState<string>('');
  const [selectedModelId, setSelectedModelId] = useState<string>('');

  const messagesEndRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLTextAreaElement>(null);
  const toastTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const pendingUpdatesRef = useRef<Map<string, Partial<ChatTurn>>>(new Map());
  const updateRafRef = useRef<number | null>(null);
  const currentTurnIdRef = useRef<string | null>(null);
  const streamingStateRef = useRef<Map<string, StreamingState>>(new Map());

  useEffect(() => {
    loadSessionData();
  }, [projectId, sessionId]);

  useEffect(() => {
    setupSocketListeners();
    return () => cleanupSocketListeners();
  }, [sessionId]);

  useEffect(() => {
    scrollToBottom();
  }, [turns]);

  useEffect(() => {
    return () => {
      if (toastTimerRef.current) {
        clearTimeout(toastTimerRef.current);
      }
      if (updateRafRef.current) {
        cancelAnimationFrame(updateRafRef.current);
      }
    };
  }, []);

  const loadSessionData = async () => {
    try {
      if (sessionId) {
        const sessionData = await chatSessionApi.get(sessionId);
        setSession(sessionData);

        const projectRef = sessionData.project;
        const projectObjectId = typeof projectRef === 'string' ? projectRef : projectRef?._id;
        if (projectObjectId) {
          const projectData = await projectApi.get(projectObjectId);
          setProject(projectData);
        }

        const turnsData = await chatSessionApi.getTurns(sessionId);
        setTurns(turnsData);
        setSessionLocked(true);

        const allProviders = await providerApi.getAll();
        setProviders(allProviders);

        const providerId = typeof sessionData.provider === 'string' 
          ? sessionData.provider 
          : sessionData.provider?._id;
        setSelectedProviderId(providerId || '');
        setSelectedModelId(sessionData.selectedModel || '');
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load session');
    } finally {
      setLoading(false);
    }
  };

  const setupSocketListeners = () => {
    socketClient.on('thinking', handleThinking);
    socketClient.on('response', handleResponse);
    socketClient.on('toolCall', handleToolCall);
    socketClient.on('workOrderComplete', handleWorkOrderComplete);
    socketClient.on('workspaceModeChanged', handleWorkspaceModeChanged);
    socketClient.on('log:entry', handleLogEntry);
    socketClient.on('status', handleStatus);
  };

  const cleanupSocketListeners = () => {
    socketClient.off('thinking', handleThinking);
    socketClient.off('response', handleResponse);
    socketClient.off('toolCall', handleToolCall);
    socketClient.off('workOrderComplete', handleWorkOrderComplete);
    socketClient.off('workspaceModeChanged', handleWorkspaceModeChanged);
    socketClient.off('log:entry', handleLogEntry);
    socketClient.off('status', handleStatus);
  };

  const scheduleUpdate = useCallback(() => {
    if (updateRafRef.current) return;
    
    updateRafRef.current = requestAnimationFrame(() => {
      const pendingEntries = Array.from(pendingUpdatesRef.current.entries());
      if (pendingEntries.length === 0) {
        updateRafRef.current = null;
        return;
      }

      setTurns(prevTurns => {
        const newTurns = [...prevTurns];
        let changed = false;

        for (const [turnId, turnUpdates] of pendingEntries) {
          const turnIndex = newTurns.findIndex(t => t._id === turnId);
          if (turnIndex === -1) continue;

          const oldTurn = newTurns[turnIndex];
          const newTurn = { ...oldTurn, ...turnUpdates };
          
          if (turnUpdates.blocks !== undefined) {
            const state = streamingStateRef.current.get(turnId);
            const currentBlockIndex = state?.currentBlockIndex ?? null;
            
            // If we have a current block index, update it in place
            if (currentBlockIndex !== null && oldTurn.blocks && oldTurn.blocks[currentBlockIndex]) {
              const oldBlocks = [...oldTurn.blocks];
              const updateBlock = turnUpdates.blocks[0];
              
              // Only update if the mode matches
              if (oldBlocks[currentBlockIndex].mode === updateBlock.mode) {
                oldBlocks[currentBlockIndex] = updateBlock;
                newTurn.blocks = oldBlocks;
              } else {
                // Mode changed, append new block and update index
                newTurn.blocks = [...oldTurn.blocks, ...turnUpdates.blocks];
                if (state) {
                  state.currentBlockIndex = newTurn.blocks.length - 1;
                }
              }
            } else {
              // No current block, append and set index
              newTurn.blocks = [...(oldTurn.blocks || []), ...turnUpdates.blocks];
              if (state && turnUpdates.blocks.length > 0) {
                state.currentBlockIndex = newTurn.blocks.length - 1;
              }
            }
          }
          if (turnUpdates.toolCalls !== undefined) {
            newTurn.toolCalls = [...(oldTurn.toolCalls || []), ...turnUpdates.toolCalls];
            newTurn.stats = {
              ...oldTurn.stats,
              toolCallCount: newTurn.toolCalls.length
            };
          }
          if (turnUpdates.status !== undefined) {
            newTurn.status = turnUpdates.status;
          }

          newTurns[turnIndex] = newTurn;
          changed = true;
        }

        return changed ? newTurns : prevTurns;
      });

      pendingUpdatesRef.current.clear();
      updateRafRef.current = null;
    });
  }, []);

  const handleThinking = useCallback((content: string) => {
    const turnId = currentTurnIdRef.current;
    if (!turnId) return;

    let state = streamingStateRef.current.get(turnId);
    if (!state) {
      state = { currentMode: null, thinkingContent: '', respondingContent: '', currentBlockIndex: null };
      streamingStateRef.current.set(turnId, state);
    }

    // Check for mode transition
    if (state.currentMode !== 'thinking') {
      // Flush previous mode
      if (state.currentMode === 'responding' && state.respondingContent) {
        pendingUpdatesRef.current.set(turnId, {
          blocks: [{
            mode: 'responding' as const,
            createdAt: new Date().toISOString(),
            content: state.respondingContent,
          }],
        });
        state.respondingContent = '';
        state.currentBlockIndex = null;
      }
      state.currentMode = 'thinking';
    }

    // Aggregate content
    state.thinkingContent += content;
    
    // Update with aggregated content
    pendingUpdatesRef.current.set(turnId, {
      blocks: [{
        mode: 'thinking' as const,
        createdAt: new Date().toISOString(),
        content: state.thinkingContent,
      }],
    });
    scheduleUpdate();
  }, [scheduleUpdate]);

  const handleResponse = useCallback((content: string) => {
    const turnId = currentTurnIdRef.current;
    if (!turnId) return;

    let state = streamingStateRef.current.get(turnId);
    if (!state) {
      state = { currentMode: null, thinkingContent: '', respondingContent: '', currentBlockIndex: null };
      streamingStateRef.current.set(turnId, state);
    }

    // Check for mode transition
    if (state.currentMode !== 'responding') {
      // Flush previous mode
      if (state.currentMode === 'thinking' && state.thinkingContent) {
        pendingUpdatesRef.current.set(turnId, {
          blocks: [{
            mode: 'thinking' as const,
            createdAt: new Date().toISOString(),
            content: state.thinkingContent,
          }],
        });
        state.thinkingContent = '';
        state.currentBlockIndex = null;
      }
      state.currentMode = 'responding';
    }

    // Aggregate content
    state.respondingContent += content;
    
    // Update with aggregated content
    pendingUpdatesRef.current.set(turnId, {
      blocks: [{
        mode: 'responding' as const,
        createdAt: new Date().toISOString(),
        content: state.respondingContent,
      }],
    });
    scheduleUpdate();
  }, [scheduleUpdate]);

  const handleToolCall = useCallback((callId: string, name: string, params: string, response: string) => {
    const turnId = currentTurnIdRef.current;
    if (!turnId) return;

    // Flush current streaming state
    const state = streamingStateRef.current.get(turnId);
    if (state) {
      const blocksToFlush: ChatTurnBlock[] = [];
      
      if (state.currentMode === 'thinking' && state.thinkingContent) {
        blocksToFlush.push({
          mode: 'thinking' as const,
          createdAt: new Date().toISOString(),
          content: state.thinkingContent,
        });
        state.thinkingContent = '';
      }
      if (state.currentMode === 'responding' && state.respondingContent) {
        blocksToFlush.push({
          mode: 'responding' as const,
          createdAt: new Date().toISOString(),
          content: state.respondingContent,
        });
        state.respondingContent = '';
      }
      
      if (blocksToFlush.length > 0) {
        pendingUpdatesRef.current.set(turnId, {
          blocks: blocksToFlush,
        });
        scheduleUpdate();
      }
      
      state.currentMode = null;
      state.currentBlockIndex = null;
    }

    // Add tool block
    pendingUpdatesRef.current.set(turnId, {
      blocks: [{
        mode: 'tool' as const,
        createdAt: new Date().toISOString(),
        content: { callId, name, parameters: params, response },
      }],
      toolCalls: [{ callId, name, parameters: params, response }],
    });
    scheduleUpdate();
  }, [scheduleUpdate]);

  const handleWorkOrderComplete = useCallback((turnId: string, success: boolean, message?: string) => {
    // Backend has already flushed and persisted all streaming content
    // Just clean up frontend streaming state and update status
    const state = streamingStateRef.current.get(turnId);
    if (state) {
      streamingStateRef.current.delete(turnId);
    }

    setTurns(prevTurns =>
      prevTurns.map(turn =>
        turn._id === turnId
          ? { ...turn, status: success ? 'finished' : 'error', errorMessage: message && !success ? message : turn.errorMessage }
          : turn
      )
    );
    setIsProcessing(false);
    currentTurnIdRef.current = null;
    if (!success) {
      setError(message || 'Work order failed');
    }
  }, []);

  const handleWorkspaceModeChanged = useCallback((mode: string) => {
    setWorkspaceMode(mode as WorkspaceMode);
  }, []);

  const handleLogEntry = useCallback((data: { level: string; message: string; timestamp: number }) => {
    setLogs(prev => [
      ...prev,
      {
        id: `log-${Date.now()}-${Math.random()}`,
        timestamp: new Date(data.timestamp),
        level: data.level,
        message: data.message,
      },
    ]);
  }, []);

  const handleStatus = useCallback((content: string) => {
    appContext?.setStatusMessage(content);
  }, [appContext]);

  const showToast = useCallback((message: string) => {
    setToast(message);
    if (toastTimerRef.current) {
      clearTimeout(toastTimerRef.current);
    }
    toastTimerRef.current = setTimeout(() => {
      setToast(null);
    }, 4000);
  }, []);

  const handleWorkspaceModeChange = async (mode: WorkspaceMode) => {
    if (!session || !project) return;

    if (mode === workspaceMode) return;

    try {
      const droneJson = localStorage.getItem('dtp_drone_registration');
      if (!droneJson) {
        showToast('No drone registration found');
        return;
      }
      const registration = JSON.parse(droneJson);
      const result = await socketClient.requestWorkspaceMode(
        registration,
        project,
        session,
        mode,
      );
      if (!result.success) {
        showToast(result.reason || `Cannot switch to ${mode} mode`);
        setWorkspaceMode(workspaceMode);
      }
    } catch (err) {
      showToast(`Failed to change workspace mode: ${err instanceof Error ? err.message : 'Unknown error'}`);
    }
  };

  const handleModeChange = async (e: React.ChangeEvent<HTMLSelectElement>) => {
    if (!session) return;

    const newMode = e.target.value as ChatSessionMode;
    if (newMode === session.mode) return;

    setIsUpdatingMode(true);
    try {
      const updatedSession = await chatSessionApi.update(session._id, { mode: newMode });
      setSession(updatedSession);
      showToast(`Session mode changed to ${newMode}`);
    } catch (err) {
      showToast(`Failed to change mode: ${err instanceof Error ? err.message : 'Unknown error'}`);
    } finally {
      setIsUpdatingMode(false);
    }
  };

  const handleProviderChange = async (e: React.ChangeEvent<HTMLSelectElement>) => {
    if (!session) return;

    const newProviderId = e.target.value;
    if (newProviderId === selectedProviderId) return;

    setIsUpdatingProvider(true);
    try {
      const updatedSession = await chatSessionApi.update(session._id, { 
        provider: newProviderId,
        selectedModel: ''
      });
      setSession(updatedSession);
      setSelectedProviderId(newProviderId);
      setSelectedModelId('');
      showToast('Provider changed. Please select a model.');
    } catch (err) {
      showToast(`Failed to change provider: ${err instanceof Error ? err.message : 'Unknown error'}`);
    } finally {
      setIsUpdatingProvider(false);
    }
  };

  const handleModelChange = async (e: React.ChangeEvent<HTMLSelectElement>) => {
    if (!session) return;

    const newModelId = e.target.value;
    if (newModelId === selectedModelId) return;

    setIsUpdatingModel(true);
    try {
      const updatedSession = await chatSessionApi.update(session._id, { 
        selectedModel: newModelId 
      });
      setSession(updatedSession);
      setSelectedModelId(newModelId);
      showToast(`Model changed`);
    } catch (err) {
      showToast(`Failed to change model: ${err instanceof Error ? err.message : 'Unknown error'}`);
    } finally {
      setIsUpdatingModel(false);
    }
  };

  const getSortedModels = (providerId: string) => {
    const provider = providers.find(p => p._id === providerId);
    if (!provider) return [];
    return [...provider.models].sort((a, b) => a.name.localeCompare(b.name));
  };

  const truncateModelName = (name: string, maxLength = 25) => {
    if (name.length <= maxLength) return name;
    return name.slice(0, maxLength - 3) + '...';
  };

  const handleSubmitPrompt = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!promptInput.trim() || isProcessing || !socketClient.connected || !sessionLocked) return;
    if (workspaceMode !== WorkspaceMode.Agent) return;
    if (!session?.selectedModel) {
      showToast('Please select a model before submitting a prompt');
      return;
    }

    const tempTurnId = `temp-${Date.now()}`;
    const userTurn: ChatTurn = {
      _id: tempTurnId,
      createdAt: new Date().toISOString(),
      user: session?.user?._id || '',
      project: session?.project?._id || projectId || '',
      session: sessionId || '',
      provider: session?.provider?._id || '',
      llm: session?.selectedModel || '',
      mode: session?.mode || 'develop',
      status: 'processing',
      prompts: { user: promptInput.trim() },
      thinking: '',
      response: '',
      toolCalls: [],
      subagents: [],
      stats: {
        toolCallCount: 0,
        inputTokens: 0,
        thinkingTokenCount: 0,
        responseTokens: 0,
        durationMs: 0,
        durationLabel: '0ms'
      }
    };

    setTurns(prev => [...prev, userTurn]);
    currentTurnIdRef.current = tempTurnId;
    setPromptInput('');
    setIsProcessing(true);
    setError('');

    socketClient.submitPrompt(promptInput.trim(), (success, data) => {
      if (success && data.turnId) {
        setTurns(prevTurns =>
          prevTurns.map(turn =>
            turn._id === tempTurnId
              ? { ...turn, _id: data.turnId! }
              : turn
          )
        );
        currentTurnIdRef.current = data.turnId;
      } else if (!success) {
        setTurns(prevTurns =>
          prevTurns.map(turn =>
            turn._id === tempTurnId
              ? { ...turn, status: 'error', errorMessage: data.message || 'Failed to submit prompt' }
              : turn
          )
        );
        setIsProcessing(false);
        currentTurnIdRef.current = null;
      }
    });
  };

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  const handleTurnUpdate = useCallback((turnId: string, updates: Partial<ChatTurn>) => {
    setTurns(prevTurns => 
      prevTurns.map(turn => 
        turn._id === turnId ? { ...turn, ...updates } : turn
      )
    );
  }, []);

  const promptDisabled = isProcessing || workspaceMode !== WorkspaceMode.Agent || !sessionLocked || !session?.selectedModel;
  const promptPlaceholder = workspaceMode !== WorkspaceMode.Agent
    ? 'Select Agent mode to enter a prompt.'
    : !session?.selectedModel
    ? 'Please select a model first.'
    : 'Enter your prompt... (Shift+Enter for new line)';

  if (loading) {
    return (
      <div className="flex-1 flex items-center justify-center bg-bg-primary">
        <p className="text-text-muted">Loading chat session...</p>
      </div>
    );
  }

  if (error && !session) {
    return (
      <div className="flex-1 flex items-center justify-center bg-bg-primary">
        <div className="text-center">
          <p className="text-red-500 mb-4">{error}</p>
          <button
            onClick={() => navigate(`/projects/${projectId}`)}
            className="px-4 py-2 bg-brand text-white rounded hover:bg-red-700 transition-colors"
          >
            Back to Project
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="flex-1 flex bg-bg-primary overflow-hidden relative">
      {/* Toast notification */}
      {toast && (
        <div className="absolute top-4 left-1/2 -translate-x-1/2 z-50 px-4 py-2 bg-bg-elevated border border-border-default rounded shadow-lg text-sm text-text-primary">
          {toast}
        </div>
      )}

      {/* Content Area */}
      <div className="flex-1 flex flex-col">
        {/* Chat View (75%) */}
        <div className="flex-1 flex flex-col overflow-hidden">
          {/* Messages */}
          <div className="flex-1 overflow-y-auto p-4 space-y-4">
            {turns.map((turn) => (
              <ChatTurnComponent
                key={turn._id}
                turn={turn}
                onUpdate={handleTurnUpdate}
              />
            ))}
            <div ref={messagesEndRef} />
          </div>

          {/* Prompt Input */}
          <div className="border-t border-border-subtle p-4 bg-bg-secondary shrink-0">
            <form onSubmit={handleSubmitPrompt} className="flex gap-2">
              <textarea
                ref={inputRef}
                value={promptInput}
                onChange={(e) => setPromptInput(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    handleSubmitPrompt(e);
                  }
                }}
                placeholder={promptPlaceholder}
                className="flex-1 px-3 py-2 bg-bg-tertiary border border-border-default rounded text-text-primary focus:border-brand focus:outline-none resize-none disabled:opacity-50"
                rows={3}
                disabled={promptDisabled}
              />
              <button
                type="submit"
                disabled={promptDisabled || !promptInput.trim()}
                className="px-6 py-2 bg-brand text-white rounded hover:bg-red-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {isProcessing ? 'Processing...' : 'Send'}
              </button>
            </form>
          </div>
        </div>

        {/* Log Panel (25%) */}
        <LogPanel
          logs={logs}
          expanded={logExpanded}
          workspaceMode={workspaceMode}
          onToggleExpand={() => setLogExpanded(!logExpanded)}
        />
      </div>

      {/* Sidebar */}
      <div className="w-80 border-l border-border-subtle bg-bg-secondary flex flex-col overflow-y-auto">
        {/* SESSION Panel */}
        <div className="border-b border-border-subtle">
          <div className="flex items-center justify-between px-4 py-2 bg-bg-tertiary">
            <h3 className="text-sm font-semibold text-text-secondary uppercase tracking-wider">
              Session
            </h3>
            <WorkspaceModeIndicator
              mode={workspaceMode}
              onChange={handleWorkspaceModeChange}
              disabled={!sessionLocked}
            />
          </div>
            <div className="p-4 space-y-3">
              <div>
                <div className="text-xs text-text-muted">Name</div>
                <div className="text-text-primary">{session?.name}</div>
              </div>
              <div className="flex gap-2">
                <div className="flex-1">
                  <div className="text-xs text-text-muted">Provider</div>
                  <select
                    value={selectedProviderId || ''}
                    onChange={handleProviderChange}
                    disabled={isUpdatingProvider}
                    className="w-full mt-1 px-2 py-1.5 bg-bg-tertiary border border-border-default rounded text-text-primary text-sm focus:border-brand focus:outline-none disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {providers.map((provider) => (
                      <option key={provider._id} value={provider._id}>
                        {provider.name}
                      </option>
                    ))}
                  </select>
                </div>
                <div className="flex-1">
                  <div className="text-xs text-text-muted">Model</div>
                  <select
                    value={selectedModelId || ''}
                    onChange={handleModelChange}
                    disabled={isUpdatingModel || !selectedProviderId}
                    className="w-full mt-1 px-2 py-1.5 bg-bg-tertiary border border-border-default rounded text-text-primary text-sm focus:border-brand focus:outline-none disabled:opacity-50 disabled:cursor-not-allowed truncate"
                  >
                    {!selectedProviderId ? (
                      <option value="">Select provider first</option>
                    ) : (
                      <>
                        <option value="">-- Select Model --</option>
                        {getSortedModels(selectedProviderId).map((model) => (
                          <option key={model.id} value={model.id}>
                            {truncateModelName(model.name)}
                          </option>
                        ))}
                      </>
                    )}
                  </select>
                </div>
              </div>
              <div>
                <div className="text-xs text-text-muted">Mode</div>
                <select
                  value={session?.mode || ChatSessionMode.Build}
                  onChange={handleModeChange}
                  disabled={isUpdatingMode}
                  className="w-full mt-1 px-2 py-1.5 bg-bg-tertiary border border-border-default rounded text-text-primary text-sm focus:border-brand focus:outline-none disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {Object.values(ChatSessionMode).map((mode) => (
                    <option key={mode} value={mode}>
                      {mode.charAt(0).toUpperCase() + mode.slice(1)}
                    </option>
                  ))}
                </select>
              </div>
            </div>
        </div>

        {/* PROJECT Panel */}
        <div className="border-b border-border-subtle">
          <div className="flex items-center justify-between px-4 py-2 bg-bg-tertiary">
            <h3 className="text-sm font-semibold text-text-secondary uppercase tracking-wider">
              Project
            </h3>
          </div>
          <div className="p-4 space-y-2">
            {project ? (
              <>
                <div>
                  <div className="text-xs text-text-muted">Name</div>
                  <div className="text-text-primary">{project.name}</div>
                </div>
                <div>
                  <div className="text-xs text-text-muted">Slug</div>
                  <div className="font-mono text-xs text-text-secondary">{project.slug}</div>
                </div>
              </>
            ) : (
              <div className="text-text-muted text-sm">Loading...</div>
            )}
          </div>
        </div>

        {/* FILES Panel */}
        <FilesPanel workspaceMode={workspaceMode} />
      </div>
    </div>
  );
}
