import React, { useState, useEffect } from 'react';
import useFlowStore from '../store/flowStore';
import type { NodeData } from '../store/flowStore';
import ReactMarkdown from 'react-markdown';
import { Play, Settings, Info, Save, ChevronLeft, ChevronRight, Maximize2, Edit3, X, Check, FileText } from 'lucide-react';

interface SidebarProps {
  isOpen: boolean;
  onToggle: () => void;
}

const Sidebar: React.FC<SidebarProps> = ({ isOpen, onToggle }) => {
  const { nodes, selectedNodeId, updateNodeData, getActiveContext } = useFlowStore();
  const [activeTab, setActiveTab] = useState<'interact' | 'settings' | 'debug'>('interact');
  const [streamBuffer, setStreamBuffer] = useState('');
  
  // Response Modal & Edit states
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [editedResponse, setEditedResponse] = useState('');
  
  // Summary states
  const [showSummaryModal, setShowSummaryModal] = useState(false);
  const [summaryModel, setSummaryModel] = useState('gpt-5-nano');
  const [isSummarizing, setIsSummarizing] = useState(false);

  const selectedNode = nodes.find((n) => n.id === selectedNodeId);

  // Reset stream buffer and modal states when node changes
  useEffect(() => {
    setStreamBuffer('');
    setIsModalOpen(false);
    setIsEditing(false);
  }, [selectedNodeId]);
  
  // Sync editedResponse when entering edit mode
  useEffect(() => {
    if (isEditing && selectedNode) {
      setEditedResponse(selectedNode.data.response || '');
    }
  }, [isEditing, selectedNode?.data.response]);

  if (!isOpen) {
    return (
      <div className="border-l border-gray-200 h-screen bg-white flex flex-col items-center py-4 w-12 z-10 transition-all duration-300">
        <button 
          onClick={onToggle}
          className="p-2 hover:bg-gray-100 rounded mb-4"
          title="Expand"
        >
          <ChevronLeft size={20} className="text-gray-500" />
        </button>
        {selectedNode && (
           <div className="writing-vertical text-xs font-bold text-gray-500 uppercase tracking-widest mt-4" style={{ writingMode: 'vertical-rl' }}>
             {selectedNode.data.label}
           </div>
        )}
      </div>
    );
  }

  if (!selectedNode) {
    return (
      <div className="w-96 border-l border-gray-200 h-screen flex flex-col bg-white shadow-xl z-10 transition-all duration-300">
        <div className="p-3 border-b border-gray-200 flex justify-between items-center bg-gray-50">
           <span className="text-sm font-medium text-gray-500">Details</span>
           <button onClick={onToggle} className="p-1 hover:bg-gray-200 rounded">
             <ChevronRight size={16} className="text-gray-500" />
           </button>
        </div>
        <div className="flex-1 p-4 bg-gray-50 text-gray-500 text-center flex flex-col justify-center">
          <p>Select a node to edit</p>
        </div>
      </div>
    );
  }

  const handleRun = async () => {
    if (!selectedNode) return;
    
    updateNodeData(selectedNode.id, { status: 'loading', response: '' });
    setStreamBuffer('');

    // Use getActiveContext which respects the user's selected traces
    const context = getActiveContext(selectedNode.id);
    
    try {
      const response = await fetch('http://localhost:8000/api/run_node_stream', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          node_id: selectedNode.id,
          incoming_contexts: [{ messages: context }], // Simple list wrap for now
          user_prompt: selectedNode.data.userPrompt,
          merge_strategy: selectedNode.data.mergeStrategy || 'smart',
          config: {
            provider: selectedNode.data.model.includes('gpt') || selectedNode.data.model === 'o3' ? 'openai' : 'google',
            model_name: selectedNode.data.model,
            temperature: selectedNode.data.temperature,
            system_prompt: selectedNode.data.systemPrompt,
            api_key: selectedNode.data.apiKey,
            enable_google_search: selectedNode.data.enableGoogleSearch !== false, // Default true
            reasoning_effort: selectedNode.data.reasoningEffort || 'medium',  // For reasoning models
          }
        })
      });

      if (!response.body) return;
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let fullResponse = '';

      while (true) {
        const { value, done } = await reader.read();
        if (done) break;
        const chunk = decoder.decode(value);
        fullResponse += chunk;
        setStreamBuffer(prev => prev + chunk);
        // We update the store less frequently or at the end to avoid too many re-renders
        // But for "live" feel we might want to update local state `streamBuffer` and sync to store at end
      }
      
      // Update final state
      // Append the new interaction to the node's output messages
      const newUserMsg = { 
        id: `msg_${Date.now()}_u`,
        role: 'user', 
        content: selectedNode.data.userPrompt 
      };
      const newAssistantMsg = { 
        id: `msg_${Date.now()}_a`,
        role: 'assistant', 
        content: fullResponse 
      };
      
      updateNodeData(selectedNode.id, { 
        status: 'success', 
        response: fullResponse,
        messages: [...context, newUserMsg, newAssistantMsg] as any 
      });
      
      // Auto-generate title using gpt-5-nano (async, non-blocking)
      // Always regenerate title after each query
      generateTitle(selectedNode.id, selectedNode.data.userPrompt, fullResponse);

    } catch (error) {
      console.error(error);
      updateNodeData(selectedNode.id, { status: 'error' });
    }
  };

  const handleChange = (field: keyof NodeData, value: any) => {
    updateNodeData(selectedNode.id, { [field]: value });
  };
  
  const handleSaveEdit = () => {
    if (!selectedNode) return;
    updateNodeData(selectedNode.id, { response: editedResponse });
    setIsEditing(false);
  };
  
  const handleCancelEdit = () => {
    setIsEditing(false);
    setEditedResponse(selectedNode?.data.response || '');
  };
  
  // Summarize response
  const handleSummarize = async () => {
    if (!selectedNode?.data.response) return;
    
    setIsSummarizing(true);
    setShowSummaryModal(false);
    
    try {
      const res = await fetch('http://localhost:8000/api/summarize', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          content: selectedNode.data.response,
          model: summaryModel
        })
      });
      
      if (res.ok) {
        const data = await res.json();
        if (data.summary) {
          // Replace response with summary
          updateNodeData(selectedNode.id, { response: data.summary });
        }
      }
    } catch (error) {
      console.error('Summarization failed:', error);
    } finally {
      setIsSummarizing(false);
    }
  };
  
  // Auto-generate title using gpt-5-nano
  const generateTitle = async (nodeId: string, userPrompt: string, response: string) => {
    try {
      const res = await fetch('http://localhost:8000/api/generate_title', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ user_prompt: userPrompt, response })
      });
      
      if (res.ok) {
        const data = await res.json();
        if (data.title) {
          updateNodeData(nodeId, { label: data.title });
        }
      }
    } catch (error) {
      console.error('Failed to generate title:', error);
      // Silently fail - keep the original title
    }
  };

  return (
    <div className="w-96 border-l border-gray-200 h-screen flex flex-col bg-white shadow-xl z-10 transition-all duration-300">
      {/* Header */}
      <div className="p-4 border-b border-gray-200 bg-gray-50 flex flex-col gap-2">
        <div className="flex justify-between items-center">
           <input 
             type="text" 
             value={selectedNode.data.label}
             onChange={(e) => handleChange('label', e.target.value)}
             className="font-bold text-lg bg-transparent border-none focus:ring-0 focus:outline-none w-full"
           />
           <button onClick={onToggle} className="p-1 hover:bg-gray-200 rounded shrink-0">
             <ChevronRight size={16} className="text-gray-500" />
           </button>
        </div>
        <div className="flex items-center justify-between mt-1">
          <div className="text-xs px-2 py-1 bg-blue-100 text-blue-700 rounded uppercase">
            {selectedNode.data.status}
          </div>
          <div className="text-xs text-gray-500">
             ID: {selectedNode.id}
          </div>
        </div>
      </div>

      {/* Tabs */}
      <div className="flex border-b border-gray-200">
        <button 
          onClick={() => setActiveTab('interact')}
          className={`flex-1 p-3 text-sm flex justify-center items-center gap-2 ${activeTab === 'interact' ? 'border-b-2 border-blue-500 text-blue-600 font-medium' : 'text-gray-600 hover:bg-gray-50'}`}
        >
          <Play size={16} /> Interact
        </button>
        <button 
          onClick={() => setActiveTab('settings')}
          className={`flex-1 p-3 text-sm flex justify-center items-center gap-2 ${activeTab === 'settings' ? 'border-b-2 border-blue-500 text-blue-600 font-medium' : 'text-gray-600 hover:bg-gray-50'}`}
        >
          <Settings size={16} /> Settings
        </button>
        <button 
          onClick={() => setActiveTab('debug')}
          className={`flex-1 p-3 text-sm flex justify-center items-center gap-2 ${activeTab === 'debug' ? 'border-b-2 border-blue-500 text-blue-600 font-medium' : 'text-gray-600 hover:bg-gray-50'}`}
        >
          <Info size={16} /> Debug
        </button>
      </div>

      {/* Content */}
      <div className="flex-1 overflow-y-auto p-4">
        {activeTab === 'interact' && (
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Model</label>
              <select 
                value={selectedNode.data.model} 
                onChange={(e) => {
                  const newModel = e.target.value;
                  // Auto-set temperature to 1 for reasoning models
                  const reasoningModels = [
                    'gpt-5', 'gpt-5-chat-latest', 'gpt-5-mini', 'gpt-5-nano', 
                    'gpt-5-pro', 'gpt-5.1', 'gpt-5.1-chat-latest', 'o3'
                  ];
                  const isReasoning = reasoningModels.includes(newModel);
                  
                  if (isReasoning) {
                    handleChange('temperature', 1);
                  }
                  handleChange('model', newModel);
                }}
                className="w-full border border-gray-300 rounded-md p-2 text-sm"
              >
                <optgroup label="Gemini">
                  <option value="gemini-2.5-flash">gemini-2.5-flash</option>
                  <option value="gemini-2.5-flash-lite">gemini-2.5-flash-lite</option>
                  <option value="gemini-3-pro-preview">gemini-3-pro-preview</option>
                </optgroup>
                <optgroup label="OpenAI (Standard)">
                  <option value="gpt-4.1">gpt-4.1</option>
                  <option value="gpt-4o">gpt-4o</option>
                </optgroup>
                <optgroup label="OpenAI (Reasoning)">
                  <option value="gpt-5">gpt-5</option>
                  <option value="gpt-5-chat-latest">gpt-5-chat-latest</option>
                  <option value="gpt-5-mini">gpt-5-mini</option>
                  <option value="gpt-5-nano">gpt-5-nano</option>
                  <option value="gpt-5-pro">gpt-5-pro</option>
                  <option value="gpt-5.1">gpt-5.1</option>
                  <option value="gpt-5.1-chat-latest">gpt-5.1-chat-latest</option>
                  <option value="o3">o3</option>
                </optgroup>
              </select>
            </div>

            {/* Trace Selector */}
            {selectedNode.data.traces && selectedNode.data.traces.length > 0 && (
              <div className="bg-gray-50 p-2 rounded border border-gray-200">
                <label className="block text-xs font-bold text-gray-500 mb-2 uppercase">Select Context Traces</label>
                <div className="space-y-1 max-h-[150px] overflow-y-auto">
                  {selectedNode.data.traces.map((trace) => {
                    const isActive = selectedNode.data.activeTraceIds?.includes(trace.id);
                    return (
                      <div key={trace.id} className="flex items-start gap-2 text-sm p-1 hover:bg-white rounded cursor-pointer"
                           onClick={() => {
                             const current = selectedNode.data.activeTraceIds || [];
                             const next = [trace.id]; // Single select mode
                             handleChange('activeTraceIds', next);
                           }}
                      >
                        <input 
                          type="radio" 
                          checked={isActive || false}
                          readOnly
                          className="mt-1"
                        />
                        <div className="flex-1">
                           <div className="flex items-center gap-2">
                             <div className="w-2 h-2 rounded-full" style={{ backgroundColor: trace.color }}></div>
                             <span className="font-mono text-xs text-gray-400">#{trace.id.slice(-4)}</span>
                           </div>
                           <div className="text-xs text-gray-600 truncate">
                             From Node: {trace.sourceNodeId}
                           </div>
                           <div className="text-[10px] text-gray-400">
                             {trace.messages.length} msgs
                           </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            )}

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">User Prompt</label>
              <textarea 
                value={selectedNode.data.userPrompt}
                onChange={(e) => handleChange('userPrompt', e.target.value)}
                className="w-full border border-gray-300 rounded-md p-2 text-sm min-h-[100px]"
                placeholder="Type your message here..."
              />
            </div>

            <button 
              onClick={handleRun}
              disabled={selectedNode.data.status === 'loading'}
              className="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 disabled:bg-blue-300 flex items-center justify-center gap-2"
            >
              {selectedNode.data.status === 'loading' ? <Loader2 className="animate-spin" size={16} /> : <Play size={16} />}
              Run Node
            </button>

            <div className="mt-6">
              <div className="flex items-center justify-between mb-2">
                <label className="block text-sm font-medium text-gray-700">Response</label>
                <div className="flex gap-1">
                  {selectedNode.data.response && (
                    <>
                      <button
                        onClick={() => setShowSummaryModal(true)}
                        disabled={isSummarizing}
                        className="p-1 hover:bg-gray-200 rounded text-gray-500 hover:text-gray-700 disabled:opacity-50"
                        title="Summarize"
                      >
                        {isSummarizing ? <Loader2 className="animate-spin" size={14} /> : <FileText size={14} />}
                      </button>
                      <button
                        onClick={() => setIsEditing(true)}
                        className="p-1 hover:bg-gray-200 rounded text-gray-500 hover:text-gray-700"
                        title="Edit Response"
                      >
                        <Edit3 size={14} />
                      </button>
                      <button
                        onClick={() => setIsModalOpen(true)}
                        className="p-1 hover:bg-gray-200 rounded text-gray-500 hover:text-gray-700"
                        title="Expand"
                      >
                        <Maximize2 size={14} />
                      </button>
                    </>
                  )}
                </div>
              </div>
              
              {isEditing ? (
                <div className="space-y-2">
                  <textarea
                    value={editedResponse}
                    onChange={(e) => setEditedResponse(e.target.value)}
                    className="w-full border border-blue-300 rounded-md p-2 text-sm min-h-[200px] font-mono focus:ring-2 focus:ring-blue-500"
                  />
                  <div className="flex gap-2 justify-end">
                    <button
                      onClick={handleCancelEdit}
                      className="px-3 py-1 text-sm text-gray-600 hover:bg-gray-100 rounded flex items-center gap-1"
                    >
                      <X size={14} /> Cancel
                    </button>
                    <button
                      onClick={handleSaveEdit}
                      className="px-3 py-1 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 flex items-center gap-1"
                    >
                      <Check size={14} /> Save
                    </button>
                  </div>
                </div>
              ) : (
                <div className="bg-gray-50 p-3 rounded-md border border-gray-200 min-h-[150px] text-sm prose prose-sm max-w-none">
                  <ReactMarkdown>{selectedNode.data.response || streamBuffer}</ReactMarkdown>
                </div>
              )}
            </div>
          </div>
        )}

        {activeTab === 'settings' && (
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Merge Strategy</label>
              <select 
                value={selectedNode.data.mergeStrategy || 'smart'} 
                onChange={(e) => handleChange('mergeStrategy', e.target.value)}
                className="w-full border border-gray-300 rounded-md p-2 text-sm"
              >
                <option value="smart">Smart (Auto-merge roles)</option>
                <option value="raw">Raw (Concatenate)</option>
              </select>
              <p className="text-xs text-gray-500 mt-1">
                Smart merge combines consecutive messages from the same role to avoid API errors.
              </p>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Temperature ({selectedNode.data.temperature})
                {[
                  'gpt-5', 'gpt-5-chat-latest', 'gpt-5-mini', 'gpt-5-nano', 
                  'gpt-5-pro', 'gpt-5.1', 'gpt-5.1-chat-latest', 'o3'
                ].includes(selectedNode.data.model) && (
                  <span className="text-xs text-orange-500 ml-2">(Locked for Reasoning Model)</span>
                )}
              </label>
              <input 
                type="range" 
                min="0" 
                max="2" 
                step="0.1"
                value={selectedNode.data.temperature}
                onChange={(e) => handleChange('temperature', parseFloat(e.target.value))}
                disabled={[
                  'gpt-5', 'gpt-5-chat-latest', 'gpt-5-mini', 'gpt-5-nano', 
                  'gpt-5-pro', 'gpt-5.1', 'gpt-5.1-chat-latest', 'o3'
                ].includes(selectedNode.data.model)}
                className="w-full disabled:opacity-50 disabled:cursor-not-allowed"
              />
            </div>

            {/* Reasoning Effort - Only for OpenAI reasoning models (except chat-latest) */}
            {[
              'gpt-5', 'gpt-5-mini', 'gpt-5-nano', 
              'gpt-5-pro', 'gpt-5.1', 'o3'
            ].includes(selectedNode.data.model) && (
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Reasoning Effort
                </label>
                <select
                  value={selectedNode.data.reasoningEffort || 'medium'}
                  onChange={(e) => handleChange('reasoningEffort', e.target.value)}
                  className="w-full border border-gray-300 rounded-md p-2 text-sm"
                >
                  <option value="low">Low (Faster, less thorough)</option>
                  <option value="medium">Medium (Balanced)</option>
                  <option value="high">High (Slower, more thorough)</option>
                </select>
                <p className="text-xs text-gray-500 mt-1">
                  Controls how much reasoning the model performs before responding. Higher = more tokens used.
                </p>
              </div>
            )}
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">API Key (Optional)</label>
              <input 
                type="password"
                value={selectedNode.data.apiKey || ''}
                onChange={(e) => handleChange('apiKey', e.target.value)}
                className="w-full border border-gray-300 rounded-md p-2 text-sm"
                placeholder="Leave empty to use backend env var"
              />
            </div>
            
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">System Prompt Override</label>
              <textarea 
                value={selectedNode.data.systemPrompt}
                onChange={(e) => handleChange('systemPrompt', e.target.value)}
                className="w-full border border-gray-300 rounded-md p-2 text-sm min-h-[100px] font-mono"
                placeholder="Global system prompt will be used if empty..."
              />
            </div>

            {(selectedNode.data.model.startsWith('gemini') || 
              selectedNode.data.model.startsWith('gpt-5') || 
              ['o3', 'o4-mini', 'gpt-4o'].includes(selectedNode.data.model)) && (
              <div className="flex items-center gap-2 mt-4">
                <input 
                  type="checkbox" 
                  id="web-search"
                  checked={selectedNode.data.enableGoogleSearch !== false} // Default to true
                  onChange={(e) => handleChange('enableGoogleSearch', e.target.checked)}
                />
                <label htmlFor="web-search" className="text-sm font-medium text-gray-700 select-none cursor-pointer">
                  Enable Web Search
                </label>
              </div>
            )}
          </div>
        )}

        {activeTab === 'debug' && (
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Active Context (Sent to LLM)</label>
              <pre className="bg-gray-900 text-gray-100 p-2 rounded text-xs overflow-x-auto">
                {JSON.stringify(getActiveContext(selectedNode.id), null, 2)}
              </pre>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Node Traces (Incoming)</label>
              <pre className="bg-gray-900 text-gray-100 p-2 rounded text-xs overflow-x-auto">
                {JSON.stringify(selectedNode.data.traces, null, 2)}
              </pre>
            </div>
          </div>
        )}
      </div>
      
      {/* Response Modal */}
      {isModalOpen && selectedNode && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={() => setIsModalOpen(false)}>
          <div 
            className="bg-white rounded-lg shadow-2xl w-[80vw] max-w-4xl max-h-[80vh] flex flex-col"
            onClick={(e) => e.stopPropagation()}
          >
            {/* Modal Header */}
            <div className="flex items-center justify-between p-4 border-b border-gray-200">
              <h3 className="font-semibold text-lg">{selectedNode.data.label} - Response</h3>
              <div className="flex gap-2">
                {!isEditing && (
                  <button
                    onClick={() => setIsEditing(true)}
                    className="px-3 py-1 text-sm text-gray-600 hover:bg-gray-100 rounded flex items-center gap-1"
                  >
                    <Edit3 size={14} /> Edit
                  </button>
                )}
                <button
                  onClick={() => { setIsModalOpen(false); setIsEditing(false); }}
                  className="p-1 hover:bg-gray-200 rounded text-gray-500"
                >
                  <X size={18} />
                </button>
              </div>
            </div>
            
            {/* Modal Content */}
            <div className="flex-1 overflow-y-auto p-6">
              {isEditing ? (
                <textarea
                  value={editedResponse}
                  onChange={(e) => setEditedResponse(e.target.value)}
                  className="w-full h-full min-h-[400px] border border-gray-300 rounded-md p-3 text-sm font-mono focus:ring-2 focus:ring-blue-500 resize-y"
                />
              ) : (
                <div className="prose prose-sm max-w-none">
                  <ReactMarkdown>{selectedNode.data.response}</ReactMarkdown>
                </div>
              )}
            </div>
            
            {/* Modal Footer (only when editing) */}
            {isEditing && (
              <div className="flex justify-end gap-2 p-4 border-t border-gray-200">
                <button
                  onClick={handleCancelEdit}
                  className="px-4 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded flex items-center gap-1"
                >
                  <X size={14} /> Cancel
                </button>
                <button
                  onClick={() => { handleSaveEdit(); setIsModalOpen(false); }}
                  className="px-4 py-2 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 flex items-center gap-1"
                >
                  <Check size={14} /> Save Changes
                </button>
              </div>
            )}
          </div>
        </div>
      )}
      
      {/* Summary Model Selection Modal */}
      {showSummaryModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={() => setShowSummaryModal(false)}>
          <div 
            className="bg-white rounded-lg shadow-2xl w-80 p-4"
            onClick={(e) => e.stopPropagation()}
          >
            <h3 className="font-semibold text-lg mb-4">Summarize Response</h3>
            
            <div className="mb-4">
              <label className="block text-sm font-medium text-gray-700 mb-2">Select Model</label>
              <select
                value={summaryModel}
                onChange={(e) => setSummaryModel(e.target.value)}
                className="w-full border border-gray-300 rounded-md p-2 text-sm"
              >
                <optgroup label="Fast (Recommended)">
                  <option value="gpt-5-nano">gpt-5-nano</option>
                  <option value="gpt-5-mini">gpt-5-mini</option>
                  <option value="gemini-2.5-flash-lite">gemini-2.5-flash-lite</option>
                  <option value="gemini-2.5-flash">gemini-2.5-flash</option>
                </optgroup>
                <optgroup label="Standard">
                  <option value="gpt-4o">gpt-4o</option>
                  <option value="gpt-5">gpt-5</option>
                </optgroup>
              </select>
            </div>
            
            <div className="flex justify-end gap-2">
              <button
                onClick={() => setShowSummaryModal(false)}
                className="px-3 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded"
              >
                Cancel
              </button>
              <button
                onClick={handleSummarize}
                className="px-3 py-2 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 flex items-center gap-1"
              >
                <FileText size={14} /> Summarize
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// Helper component for icon
const Loader2 = ({ className, size }: { className?: string, size?: number }) => (
  <svg 
    xmlns="http://www.w3.org/2000/svg" 
    width={size || 24} 
    height={size || 24} 
    viewBox="0 0 24 24" 
    fill="none" 
    stroke="currentColor" 
    strokeWidth="2" 
    strokeLinecap="round" 
    strokeLinejoin="round" 
    className={className}
  >
    <path d="M21 12a9 9 0 1 1-6.219-8.56" />
  </svg>
);

export default Sidebar;

