import React, { useState } from 'react';
import { ChevronRight, ChevronDown, Pin, X, Hash, User, Check, Send, Filter, Trash2 } from 'lucide-react';

export default function FactumNotesMockup() {
  const [selectedCase, setSelectedCase] = useState('CASE-2025-001');
  const [selectedEvidence, setSelectedEvidence] = useState('HDD-001');
  const [activeCase, setActiveCase] = useState('CASE-2025-001');
  const [activeEvidence, setActiveEvidence] = useState('HDD-001');
  const [expandedCases, setExpandedCases] = useState({ 'CASE-2025-001': true });
  const [noteInput, setNoteInput] = useState('');
  const [showGoals, setShowGoals] = useState(true);
  const [showIocs, setShowIocs] = useState(true);
  const [llmActive, setLlmActive] = useState(false);
  const [llmInput, setLlmInput] = useState('');
  const [llmMessages, setLlmMessages] = useState([
    { role: 'assistant', content: 'Ready to assist with analysis. Ask me about timeline correlation, IoC enrichment, or next investigation steps.' }
  ]);
  const [filterTag, setFilterTag] = useState(null);

  // Mock data
  const cases = {
    'CASE-2025-001': {
      name: 'Financial Fraud Investigation',
      evidences: ['HDD-001', 'USB-STICK-001', 'MEMORY-DUMP-001']
    },
    'CASE-2024-089': {
      name: 'Corporate Espionage',
      evidences: ['LAPTOP-001', 'PHONE-BACKUP-001']
    }
  };

  const [notes, setNotes] = useState([
    {
      id: 1,
      caseId: 'CASE-2025-001',
      evidenceId: 'HDD-001',
      timestamp: '2025-12-22 14:32:15 UTC',
      content: 'Initial analysis of disk image reveals potential data exfiltration. Found suspicious PowerShell script at C:\\Users\\john.doe\\AppData\\Local\\Temp\\export.ps1. Script contains Base64-encoded payload attempting to connect to 192.168.45.123:4444 and download file from https://malicious-domain.com/payload.exe. MD5 hash of script: 5d41402abc4b2a76b9719d911017c592',
      tags: ['initial-analysis', 'powershell', 'network-activity'],
      signatures: ['Alice Johnson', 'Bob Smith'],
      iocs: ['192.168.45.123:4444', 'https://malicious-domain.com/payload.exe', '5d41402abc4b2a76b9719d911017c592'],
      signed: true,
      pinned: false
    },
    {
      id: 2,
      caseId: 'CASE-2025-001',
      evidenceId: 'HDD-001',
      timestamp: '2025-12-22 15:45:02 UTC',
      content: 'Registry analysis shows persistence mechanism established via Run key. Malware creates scheduled task named "SystemUpdate" executing C:\\Windows\\Temp\\svchost.exe every 30 minutes. SHA256: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
      tags: ['persistence', 'registry', 'scheduled-task'],
      signatures: ['Alice Johnson'],
      iocs: ['C:\\Windows\\Temp\\svchost.exe', 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'],
      signed: true,
      pinned: false
    },
    {
      id: 3,
      caseId: 'CASE-2025-001',
      evidenceId: 'HDD-001',
      timestamp: '2025-12-22 16:20:38 UTC',
      content: 'Browser history extraction complete. User visited cryptocurrency exchange wallet at 1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa multiple times between Dec 15-20. Timeline correlates with unauthorized transfers.',
      tags: ['timeline', 'browser-history', 'cryptocurrency'],
      signatures: ['Alice Johnson'],
      iocs: ['1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa'],
      signed: true,
      pinned: true
    },
    {
      id: 4,
      caseId: 'CASE-2025-001',
      evidenceId: 'USB-STICK-001',
      timestamp: '2025-12-22 17:10:22 UTC',
      content: 'USB device analysis reveals autorun.inf configured to execute malicious payload. Device contains encrypted archive with password hint referencing internal project codename.',
      tags: ['usb-analysis', 'autorun', 'encryption'],
      signatures: ['Bob Smith'],
      iocs: [],
      signed: true,
      pinned: false
    },
    {
      id: 5,
      caseId: 'CASE-2024-089',
      evidenceId: 'LAPTOP-001',
      timestamp: '2025-12-21 10:15:00 UTC',
      content: 'Corporate laptop shows evidence of unauthorized remote access tool installation. RustDesk client configured with external server 203.0.113.50:21116',
      tags: ['remote-access', 'corporate', 'initial-analysis'],
      signatures: ['Alice Johnson'],
      iocs: ['203.0.113.50:21116'],
      signed: true,
      pinned: false
    },
    {
      id: 6,
      caseId: 'CASE-2025-001',
      evidenceId: null, // Case-level note
      timestamp: '2025-12-22 13:00:00 UTC',
      content: 'Case opened: Financial fraud investigation involving potential cryptocurrency theft. Initial evidence suggests internal employee involvement based on access patterns.',
      tags: ['case-overview', 'fraud', 'cryptocurrency'],
      signatures: ['Alice Johnson'],
      iocs: [],
      signed: true,
      pinned: false
    },
    {
      id: 7,
      caseId: 'CASE-2025-001',
      evidenceId: null, // Case-level note
      timestamp: '2025-12-22 18:00:00 UTC',
      content: 'Daily summary: Evidence from multiple devices shows coordinated exfiltration attempt. Recommend expanding investigation to include network logs and employee workstation forensics.',
      tags: ['summary', 'coordination'],
      signatures: ['Alice Johnson'],
      iocs: [],
      signed: true,
      pinned: false
    }
  ]);

  const [showNestedNotes, setShowNestedNotes] = useState(true);

  const [pinnedNotes, setPinnedNotes] = useState([
    {
      id: 'pin-1',
      content: 'CRITICAL: Check all PowerShell execution logs between Dec 15-20',
      timestamp: '2025-12-22 13:00:00 UTC'
    }
  ]);

  const investigativeGoals = [
    'Identify initial infection vector and timeline',
    'Map complete network of compromised systems',
    'Determine data exfiltration extent and destination',
    'Establish attribution indicators'
  ];

  const toggleCase = (caseId) => {
    setExpandedCases(prev => ({ ...prev, [caseId]: !prev[caseId] }));
  };

  const extractIocs = (text) => {
    const iocs = [];
    
    // IPv4 with port
    const ipv4Pattern = /\b(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\b/g;
    const ipMatches = text.match(ipv4Pattern);
    if (ipMatches) iocs.push(...ipMatches);
    
    // URLs
    const urlPattern = /https?:\/\/[^\s]+/g;
    const urlMatches = text.match(urlPattern);
    if (urlMatches) iocs.push(...urlMatches);
    
    // MD5
    const md5Pattern = /\b[a-f0-9]{32}\b/gi;
    const md5Matches = text.match(md5Pattern);
    if (md5Matches) iocs.push(...md5Matches);
    
    // SHA256
    const sha256Pattern = /\b[a-f0-9]{64}\b/gi;
    const sha256Matches = text.match(sha256Pattern);
    if (sha256Matches) iocs.push(...sha256Matches);
    
    // Bitcoin addresses (simplified)
    const btcPattern = /\b[13][a-km-zA-HJ-NP-Z1-9]{25,34}\b/g;
    const btcMatches = text.match(btcPattern);
    if (btcMatches) iocs.push(...btcMatches);
    
    // File paths
    const pathPattern = /[A-Z]:\\(?:[^\s\\]+\\)*[^\s\\]+\.[a-z]{2,4}/gi;
    const pathMatches = text.match(pathPattern);
    if (pathMatches) iocs.push(...pathMatches);
    
    return [...new Set(iocs)];
  };

  const extractTags = (text) => {
    const tagPattern = /#([a-z0-9-]+)/gi;
    const matches = text.match(tagPattern);
    return matches ? [...new Set(matches.map(t => t.substring(1).toLowerCase()))] : [];
  };

  const addNote = () => {
    if (!noteInput.trim()) return;
    
    const now = new Date();
    const timestamp = now.toISOString().replace('T', ' ').substring(0, 19) + ' UTC';
    const iocs = extractIocs(noteInput);
    const tags = extractTags(noteInput);
    
    const newNote = {
      id: Math.max(...notes.map(n => n.id), 0) + 1,
      caseId: selectedCase,
      evidenceId: selectedEvidence,
      timestamp,
      content: noteInput,
      tags,
      signatures: ['Alice Johnson'],
      iocs,
      signed: true,
      pinned: false
    };
    
    setNotes([...notes, newNote]);
    setNoteInput('');
  };

  const togglePin = (noteId) => {
    setNotes(notes.map(note => 
      note.id === noteId ? { ...note, pinned: !note.pinned } : note
    ));
  };

  const deleteNote = (noteId) => {
    setNotes(notes.filter(n => n.id !== noteId));
  };

  const sendLlmMessage = () => {
    if (!llmInput.trim()) return;
    
    const userMsg = { role: 'user', content: llmInput };
    setLlmMessages([...llmMessages, userMsg]);
    
    // Simulate AI response
    setTimeout(() => {
      let response = '';
      const input = llmInput.toLowerCase();
      
      if (input.includes('timeline') || input.includes('chronology')) {
        response = 'Based on the timestamps, the attack sequence appears to be: 1) Initial compromise via PowerShell script (14:32), 2) Persistence establishment through registry modification (15:45), 3) Data exfiltration to cryptocurrency wallet (16:20). Consider examining system logs between these timestamps for additional pivot points.';
      } else if (input.includes('ioc') || input.includes('indicator')) {
        response = 'I\'ve identified 6 unique IoCs across your notes. The IP address 192.168.45.123:4444 appears to be a C2 server. I recommend: 1) Checking if this IP appears in other evidence items, 2) Searching for the malicious domain in DNS logs, 3) Validating the file hashes against VirusTotal.';
      } else if (input.includes('next') || input.includes('recommend')) {
        response = 'Recommended next steps: 1) Analyze the PowerShell execution history for the timeframe Dec 15-20, 2) Extract and decrypt the USB archive if possible, 3) Cross-reference the cryptocurrency wallet address with blockchain explorers for transaction analysis, 4) Check network logs for communication with 192.168.45.123.';
      } else {
        response = 'I can help analyze your notes, correlate timelines, enrich IoCs, or suggest investigation steps. What specific aspect would you like assistance with?';
      }
      
      const aiMsg = { role: 'assistant', content: response };
      setLlmMessages(prev => [...prev, aiMsg]);
    }, 500);
    
    setLlmInput('');
  };

  const handleKeyDown = (e, callback) => {
    if (e.key === 'Enter' && e.ctrlKey) {
      e.preventDefault();
      callback();
    }
  };

  // Filter notes based on selection and tag filter
  const filteredNotes = notes.filter(note => {
    const matchesCase = note.caseId === selectedCase;
    const matchesTag = !filterTag || note.tags.includes(filterTag);
    
    if (!matchesCase || !matchesTag) return false;
    
    // If viewing a specific evidence, only show notes from that evidence
    if (selectedEvidence) {
      return note.evidenceId === selectedEvidence;
    }
    
    // If viewing case-level (no evidence selected)
    // Show case-level notes always
    if (!note.evidenceId) {
      return true;
    }
    
    // Show evidence notes only if nested toggle is on
    return showNestedNotes;
  }).sort((a, b) => {
    // Sort chronologically by timestamp
    return new Date(a.timestamp) - new Date(b.timestamp);
  });

  // Get all unique tags from filtered notes
  const allTags = [...new Set(filteredNotes.flatMap(note => note.tags))];

  // Get extracted IoCs from filtered notes and organize by type
  const iocsByType = filteredNotes.reduce((acc, note) => {
    note.iocs.forEach(ioc => {
      let type = 'Unknown';
      if (/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/.test(ioc)) type = 'IPv4';
      else if (/^https?:\/\//.test(ioc)) type = 'URL';
      else if (/^[a-f0-9]{32}$/i.test(ioc)) type = 'MD5';
      else if (/^[a-f0-9]{64}$/i.test(ioc)) type = 'SHA256';
      else if (/^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$/.test(ioc)) type = 'Bitcoin';
      else if (/^[A-Z]:\\/.test(ioc)) type = 'File Path';
      
      if (!acc[type]) {
        acc[type] = [];
      }
      if (!acc[type].find(item => item === ioc)) {
        acc[type].push(ioc);
      }
    });
    return acc;
  }, {});

  // Get pinned notes from the currently selected case (not filtered by evidence)
  const displayPinnedNotes = notes.filter(n => n.pinned && n.caseId === selectedCase);

  // State for IoC tree expansion
  const [expandedIocTypes, setExpandedIocTypes] = useState({});

  const toggleIocType = (type) => {
    setExpandedIocTypes(prev => ({ ...prev, [type]: !prev[type] }));
  };

  const highlightIocs = (text, iocs) => {
    if (!iocs || iocs.length === 0) return text;
    
    let result = text;
    const parts = [];
    let lastIndex = 0;
    
    // Sort IOCs by their position in text
    const positions = [];
    iocs.forEach(ioc => {
      const index = result.indexOf(ioc);
      if (index !== -1) {
        positions.push({ ioc, index });
      }
    });
    positions.sort((a, b) => a.index - b.index);
    
    positions.forEach(({ ioc, index }) => {
      if (index >= lastIndex) {
        parts.push(result.substring(lastIndex, index));
        parts.push(<span key={index} className="bg-amber-100 text-amber-900 px-1 rounded font-mono text-sm border border-amber-300">{ioc}</span>);
        lastIndex = index + ioc.length;
      }
    });
    parts.push(result.substring(lastIndex));
    
    return parts;
  };

  return (
    <div className="h-screen flex flex-col bg-stone-50 text-stone-800 font-mono">
      {/* Menu Bar */}
      <div className="bg-amber-900 border-b border-amber-800 px-4 py-2 flex items-center space-x-6">
        <span className="text-amber-50 font-bold text-lg">FACTUM-NOTES</span>
        <button className="text-amber-100 hover:text-amber-50 transition-colors">File</button>
        <button className="text-amber-100 hover:text-amber-50 transition-colors">View</button>
        <button className="text-amber-100 hover:text-amber-50 transition-colors">Settings</button>
        <button className="text-amber-100 hover:text-amber-50 transition-colors">Help</button>
      </div>

      {/* Main Content Area */}
      <div className="flex-1 flex overflow-hidden">
        {/* Left Sidebar - Case/Evidence Tree */}
        <div className="w-72 bg-stone-100 border-r border-stone-300 flex flex-col">
          <div className="p-3 border-b border-stone-300">
            <h3 className="text-xs uppercase tracking-wider text-stone-600 mb-1">Case Structure</h3>
            <p className="text-xs text-stone-500 flex items-center">
              <span className="inline-block w-2 h-2 rounded-full bg-green-600 mr-1"></span> = Active for CLI notes
            </p>
          </div>
          
          <div className="flex-1 overflow-y-auto p-2">
            {Object.entries(cases).map(([caseId, caseData]) => (
              <div key={caseId} className="mb-2">
                <div 
                  className={`flex items-center space-x-2 px-2 py-2 rounded cursor-pointer transition-colors ${
                    selectedCase === caseId && !selectedEvidence ? 'bg-amber-100 text-amber-900 border border-amber-300' : 'hover:bg-stone-200'
                  }`}
                  onClick={() => {
                    setSelectedCase(caseId);
                    setSelectedEvidence(null);
                    toggleCase(caseId);
                  }}
                >
                  {expandedCases[caseId] ? 
                    <ChevronDown className="w-4 h-4" /> : 
                    <ChevronRight className="w-4 h-4" />
                  }
                  <span 
                    className={`inline-block w-2 h-2 rounded-full cursor-pointer transition-colors ${
                      activeCase === caseId && !activeEvidence ? 'bg-green-600' : 'bg-stone-400 hover:bg-green-400'
                    }`}
                    onClick={(e) => {
                      e.stopPropagation();
                      setActiveCase(caseId);
                      setActiveEvidence(null);
                    }}
                    title={activeCase === caseId && !activeEvidence ? "Active for CLI notes" : "Set as active for CLI notes"}
                  />
                  <span className="text-sm font-semibold flex-1">{caseId}</span>
                </div>
                
                {expandedCases[caseId] && (
                  <div className="ml-6 mt-1 space-y-1">
                    <div className="text-xs text-stone-600 mb-2">{caseData.name}</div>
                    {caseData.evidences.map(evidence => (
                      <div
                        key={evidence}
                        className={`px-2 py-1.5 rounded text-sm cursor-pointer transition-colors flex items-center ${
                          selectedEvidence === evidence ? 'bg-amber-50 text-amber-900 border-l-2 border-amber-700' : 'hover:bg-stone-200'
                        }`}
                        onClick={() => {
                          setSelectedCase(caseId);
                          setSelectedEvidence(evidence);
                        }}
                      >
                        <span 
                          className={`inline-block w-2 h-2 rounded-full mr-2 cursor-pointer transition-colors ${
                            activeCase === caseId && activeEvidence === evidence ? 'bg-green-600' : 'bg-stone-400 hover:bg-green-400'
                          }`}
                          onClick={(e) => {
                            e.stopPropagation();
                            setActiveCase(caseId);
                            setActiveEvidence(evidence);
                          }}
                          title={activeCase === caseId && activeEvidence === evidence ? "Active for CLI notes" : "Set as active for CLI notes"}
                        />
                        <span className="flex-1">{evidence}</span>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            ))}
          </div>

          <div className="p-3 border-t border-stone-300 space-y-2">
            <button className="w-full px-3 py-2 bg-amber-700 hover:bg-amber-800 text-amber-50 rounded text-sm transition-colors">
              + New Case
            </button>
            <button className="w-full px-3 py-2 bg-red-100 hover:bg-red-200 text-red-800 border border-red-300 rounded text-sm transition-colors">
              − Delete Case
            </button>
          </div>
        </div>

        {/* Central Content Area */}
        <div className="flex-1 flex flex-col">
          {/* Filter Bar */}
          <div className="border-b border-stone-300 px-4 py-2 bg-stone-100 flex items-center justify-between">
            <div className="flex items-center space-x-4">
              <div className="flex items-center space-x-2">
                <Filter className="w-4 h-4 text-stone-600" />
                <span className="text-xs text-stone-600">Filter by tag:</span>
                <select 
                  value={filterTag || ''}
                  onChange={(e) => setFilterTag(e.target.value || null)}
                  className="bg-white border border-stone-300 rounded px-2 py-1 text-xs text-stone-800 focus:outline-none focus:border-amber-700 focus:ring-1 focus:ring-amber-700"
                >
                  <option value="">All tags</option>
                  {allTags.map(tag => (
                    <option key={tag} value={tag}>#{tag}</option>
                  ))}
                </select>
                {filterTag && (
                  <button 
                    onClick={() => setFilterTag(null)}
                    className="text-xs text-red-700 hover:text-red-800 transition-colors"
                  >
                    Clear filter
                  </button>
                )}
              </div>
              {!selectedEvidence && (
                <label className="flex items-center space-x-2 cursor-pointer">
                  <input 
                    type="checkbox" 
                    checked={showNestedNotes}
                    onChange={(e) => setShowNestedNotes(e.target.checked)}
                    className="w-3 h-3 text-amber-700 focus:ring-amber-700 rounded"
                  />
                  <span className="text-xs text-stone-700">Show nested evidence notes</span>
                </label>
              )}
            </div>
            <span className="text-xs text-stone-600">{filteredNotes.length} note{filteredNotes.length !== 1 ? 's' : ''}</span>
          </div>

          {/* Notes Display */}
          <div className="flex-1 overflow-y-auto p-4 space-y-3">
            {filteredNotes.length === 0 ? (
              <div className="flex items-center justify-center h-full text-stone-500 text-sm">
                No notes for this selection
              </div>
            ) : (
              filteredNotes.map((note, idx) => {
                // Determine if this is a nested note (evidence note when viewing case-level)
                const isNested = !selectedEvidence && note.evidenceId;
                
                // For tree structure, check if next note is also nested
                const nextNote = filteredNotes[idx + 1];
                const isLastNested = isNested && (!nextNote || !nextNote.evidenceId);
                const treeSymbol = isNested ? (isLastNested ? '└──' : '├──') : '';
                
                return (
                  <div key={note.id} className={`bg-white border border-stone-300 rounded-lg p-4 hover:border-amber-400 hover:shadow-sm transition-all ${isNested ? 'ml-12' : ''}`}>
                    {/* Timestamp and Evidence Badge */}
                    <div className="flex items-center justify-between mb-3">
                      <div className="flex items-center space-x-2 flex-1">
                        {isNested && (
                          <>
                            <span className="text-stone-500 font-mono text-xs flex-shrink-0">{treeSymbol}</span>
                            <span className="text-xs font-semibold text-stone-700 bg-amber-100 px-2 py-1 rounded border border-amber-300 flex-shrink-0">
                              {note.evidenceId}
                            </span>
                          </>
                        )}
                        <span className="text-amber-800 text-sm font-bold">{note.timestamp}</span>
                      </div>
                      <div className="flex items-center space-x-2">
                        <Pin 
                          className={`w-4 h-4 cursor-pointer transition-colors ${
                            note.pinned ? 'text-amber-700 fill-amber-700' : 'text-stone-400 hover:text-amber-700'
                          }`}
                          onClick={() => togglePin(note.id)}
                        />
                        <Trash2 
                          className="w-4 h-4 text-stone-400 hover:text-red-700 cursor-pointer transition-colors"
                          onClick={() => {
                            if (window.confirm('Delete this note?')) {
                              deleteNote(note.id);
                            }
                          }}
                        />
                      </div>
                    </div>
                    
                    {/* Content */}
                    <div className="text-sm text-stone-700 leading-relaxed mb-3">
                      {highlightIocs(note.content, note.iocs)}
                    </div>
                    
                    {/* Tags */}
                    {note.tags && note.tags.length > 0 && (
                      <div className="flex flex-wrap gap-2 mb-3">
                        {note.tags.map(tag => (
                          <span 
                            key={tag} 
                            className="px-2 py-1 bg-blue-50 text-blue-800 rounded text-xs border border-blue-200 cursor-pointer hover:bg-blue-100 transition-colors"
                            onClick={() => setFilterTag(tag)}
                          >
                            #{tag}
                          </span>
                        ))}
                      </div>
                    )}
                    
                    {/* Signatures */}
                    <div className="flex items-center space-x-2 pt-2 border-t border-stone-200">
                      <Check className="w-3 h-3 text-green-700" />
                      <span className="text-xs text-stone-600">Signed by:</span>
                      {note.signatures.map((signer, idx) => (
                        <span 
                          key={idx}
                          className="group relative"
                        >
                          <User className="w-4 h-4 text-green-700 cursor-help" />
                          <span className="absolute bottom-full left-1/2 -translate-x-1/2 mb-1 px-2 py-1 bg-stone-800 text-amber-50 text-xs rounded opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap pointer-events-none z-10">
                            {signer}
                          </span>
                        </span>
                      ))}
                    </div>
                  </div>
                );
              })
            )}
          </div>

          {/* Input Area */}
          <div className="border-t border-stone-300 p-4 bg-stone-100">
            <textarea
              value={noteInput}
              onChange={(e) => setNoteInput(e.target.value)}
              onKeyDown={(e) => handleKeyDown(e, addNote)}
              placeholder="Enter forensic note... Use #tags for categorization. IoCs will be auto-extracted. (Ctrl+Enter to submit)"
              className="w-full h-24 bg-white border border-stone-300 rounded px-3 py-2 text-sm text-stone-800 placeholder-stone-500 focus:outline-none focus:border-amber-700 focus:ring-1 focus:ring-amber-700 resize-none"
            />
            <div className="flex items-center justify-between mt-2">
              <span className="text-xs text-stone-600">IoCs will be auto-extracted | GPG signing enabled</span>
              <button 
                onClick={addNote}
                className="px-4 py-1.5 bg-amber-700 hover:bg-amber-800 text-amber-50 rounded text-sm transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                disabled={!noteInput.trim()}
              >
                Add Note
              </button>
            </div>
          </div>
        </div>

        {/* Right Sidebar - Information Panel */}
        <div className="w-80 bg-stone-100 border-l border-stone-300 flex flex-col overflow-y-auto">
          {/* Investigative Goals - Always at top */}
          <div className="border-b border-stone-300">
            <div 
              className="p-3 bg-stone-200 flex items-center justify-between cursor-pointer hover:bg-stone-250 transition-colors"
              onClick={() => setShowGoals(!showGoals)}
            >
              <h3 className="text-xs uppercase tracking-wider text-stone-700">Investigative Goals</h3>
              <div className="flex items-center space-x-2">
                <button 
                  onClick={(e) => {
                    e.stopPropagation();
                    alert('Edit goals dialog would open here');
                  }}
                  className="p-1 hover:bg-stone-300 rounded transition-colors"
                  title="Edit Goals"
                >
                  <svg className="w-3 h-3 text-stone-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                  </svg>
                </button>
                {showGoals ? <ChevronDown className="w-4 h-4" /> : <ChevronRight className="w-4 h-4" />}
              </div>
            </div>
            {showGoals && (
              <div className="p-3">
                <ol className="space-y-2 text-xs text-stone-700">
                  {investigativeGoals.map((goal, idx) => (
                    <li key={idx} className="flex items-start">
                      <span className="text-amber-800 mr-2 font-semibold">{idx + 1}.</span>
                      <span>{goal}</span>
                    </li>
                  ))}
                </ol>
              </div>
            )}
          </div>

          {/* Pinned Notes */}
          {displayPinnedNotes.length > 0 && (
            <div className="border-b border-stone-300">
              <div className="p-3 bg-stone-200">
                <h3 className="text-xs uppercase tracking-wider text-stone-700 flex items-center">
                  <Pin className="w-3 h-3 mr-2" />
                  Pinned Notes
                </h3>
              </div>
              <div className="p-3 space-y-2 max-h-64 overflow-y-auto" style={{minHeight: '80px'}}>
                {displayPinnedNotes.map(note => (
                  <div key={note.id} className="bg-green-50 border border-green-300 rounded p-3">
                    <div className="flex items-start justify-between mb-2">
                      <div className="flex-1">
                        <span className="text-xs text-green-800">{note.timestamp}</span>
                        <div className="text-xs text-stone-600 mt-1">
                          {note.caseId}{note.evidenceId ? ` > ${note.evidenceId}` : ''}
                        </div>
                      </div>
                      <X 
                        className="w-3 h-3 text-stone-500 hover:text-red-700 cursor-pointer transition-colors flex-shrink-0"
                        onClick={() => togglePin(note.id)}
                      />
                    </div>
                    <p className="text-xs text-stone-800 line-clamp-3">{note.content}</p>
                    {note.tags && note.tags.length > 0 && (
                      <div className="flex flex-wrap gap-1 mt-2">
                        {note.tags.map(tag => (
                          <span key={tag} className="px-1.5 py-0.5 bg-blue-100 text-blue-800 rounded text-xs border border-blue-200">
                            #{tag}
                          </span>
                        ))}
                      </div>
                    )}
                  </div>
                ))}
              </div>
              {/* Resize Handle */}
              <div className="h-1 bg-stone-300 hover:bg-amber-600 cursor-ns-resize transition-colors" title="Drag to resize"></div>
            </div>
          )}

          {/* Extracted IOCs */}
          <div className="border-b border-stone-300">
            <div 
              className="p-3 bg-stone-200 flex items-center justify-between cursor-pointer hover:bg-stone-250 transition-colors"
              onClick={() => setShowIocs(!showIocs)}
            >
              <h3 className="text-xs uppercase tracking-wider text-stone-700 flex items-center">
                <Hash className="w-3 h-3 mr-2" />
                Extracted IOCs ({Object.values(iocsByType).flat().length})
              </h3>
              {showIocs ? <ChevronDown className="w-4 h-4" /> : <ChevronRight className="w-4 h-4" />}
            </div>
            {showIocs && (
              <div className="p-3 space-y-1 max-h-64 overflow-y-auto" style={{minHeight: '100px'}}>
                {Object.keys(iocsByType).length === 0 ? (
                  <p className="text-xs text-stone-500">No IoCs extracted yet</p>
                ) : (
                  Object.entries(iocsByType).map(([type, iocs]) => (
                    <div key={type}>
                      <div 
                        className="flex items-center space-x-1 cursor-pointer hover:bg-stone-100 py-1 px-2 rounded transition-colors"
                        onClick={() => toggleIocType(type)}
                      >
                        <span className="text-stone-700 font-mono text-xs">
                          {expandedIocTypes[type] ? '▼' : '▶'}
                        </span>
                        <span className="text-xs font-semibold text-amber-800">
                          {type} ({iocs.length})
                        </span>
                      </div>
                      {expandedIocTypes[type] && (
                        <div className="ml-4 space-y-1">
                          {iocs.map((ioc, idx) => (
                            <div 
                              key={idx}
                              className="flex items-start space-x-1 py-1 px-2 hover:bg-amber-50 rounded cursor-pointer transition-colors"
                              onClick={() => alert(`Filter notes containing: ${ioc}`)}
                              title="Click to filter notes containing this IoC"
                            >
                              <span className="text-stone-500 font-mono text-xs flex-shrink-0">
                                {idx === iocs.length - 1 ? '└──' : '├──'}
                              </span>
                              <span className="text-xs text-stone-700 font-mono break-all">{ioc}</span>
                            </div>
                          ))}
                        </div>
                      )}
                    </div>
                  ))
                )}
              </div>
            )}
            {/* Resize Handle */}
            <div className="h-1 bg-stone-300 hover:bg-amber-600 cursor-ns-resize transition-colors" title="Drag to resize"></div>
          </div>

          {/* LLM Interface */}
          <div className="flex-1 flex flex-col" style={{minHeight: '200px'}}>
            <div className="p-3 bg-stone-200 flex items-center justify-between">
              <h3 className="text-xs uppercase tracking-wider text-stone-700">AI Assistant</h3>
              <button 
                onClick={() => setLlmActive(!llmActive)}
                className={`px-2 py-1 rounded text-xs transition-colors ${
                  llmActive ? 'bg-green-100 text-green-800 border border-green-300' : 'bg-stone-300 text-stone-600'
                }`}
              >
                {llmActive ? 'ACTIVE' : 'INACTIVE'}
              </button>
            </div>
            {llmActive && (
              <div className="flex-1 flex flex-col p-3 min-h-0">
                {/* Quick Action Buttons */}
                <div className="mb-3 space-y-2">
                  <button 
                    onClick={() => {
                      const assessMsg = { role: 'user', content: '[Assess Investigation] Compare current notes with investigative goals' };
                      setLlmMessages([...llmMessages, assessMsg]);
                      setTimeout(() => {
                        const response = { role: 'assistant', content: 'Based on your notes, you\'ve made progress on goals 1 and 3. Goal 2 (mapping compromised systems) needs attention - consider analyzing network logs from the malicious IP 192.168.45.123. Goal 4 (attribution) is still pending - the cryptocurrency wallet and PowerShell techniques could be researched for similar campaigns.' };
                        setLlmMessages(prev => [...prev, response]);
                      }, 500);
                    }}
                    className="w-full px-3 py-2 bg-blue-100 hover:bg-blue-200 text-blue-800 border border-blue-300 rounded text-xs transition-colors text-left flex items-center"
                  >
                    <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4" />
                    </svg>
                    Assess Investigation
                  </button>
                  
                  <button 
                    onClick={() => {
                      const suggestMsg = { role: 'user', content: '[Suggest Goals] Recommend investigation directions' };
                      setLlmMessages([...llmMessages, suggestMsg]);
                      setTimeout(() => {
                        const response = { role: 'assistant', content: 'Based on your findings, I suggest:\n1. Timeline all PowerShell executions and correlate with network connections\n2. Analyze the encrypted USB archive - password hint may lead to internal knowledge\n3. Search for similar Bitcoin wallet in other evidence items\n4. Research the hash 5d41402abc4b2a76b9719d911017c592 against threat intelligence databases\n\nWould you like me to add these to your investigative goals?' };
                        setLlmMessages(prev => [...prev, response]);
                      }, 500);
                    }}
                    className="w-full px-3 py-2 bg-green-100 hover:bg-green-200 text-green-800 border border-green-300 rounded text-xs transition-colors text-left flex items-center"
                  >
                    <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
                    </svg>
                    Suggest Goals
                  </button>
                </div>

                {/* Conversation History */}
                <div className="flex-1 bg-white border border-stone-300 rounded p-3 mb-2 overflow-y-auto text-xs space-y-2">
                  {llmMessages.map((msg, idx) => (
                    <div key={idx} className={`${msg.role === 'user' ? 'text-blue-800' : 'text-stone-700'}`}>
                      <span className="font-semibold">{msg.role === 'user' ? '👤 You' : '🤖 AI'}:</span> {msg.content}
                    </div>
                  ))}
                </div>

                {/* General Query Input */}
                <div className="flex space-x-2">
                  <input 
                    type="text"
                    value={llmInput}
                    onChange={(e) => setLlmInput(e.target.value)}
                    onKeyDown={(e) => {
                      if (e.key === 'Enter') {
                        e.preventDefault();
                        sendLlmMessage();
                      }
                    }}
                    placeholder="Ask the AI..."
                    className="flex-1 bg-white border border-stone-300 rounded px-2 py-1.5 text-xs text-stone-800 placeholder-stone-500 focus:outline-none focus:border-amber-700 focus:ring-1 focus:ring-amber-700"
                  />
                  <button 
                    onClick={sendLlmMessage}
                    disabled={!llmInput.trim()}
                    className="px-3 py-1.5 bg-amber-700 hover:bg-amber-800 text-amber-50 rounded text-xs transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    <Send className="w-3 h-3" />
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Status Bar */}
      <div className="bg-amber-900 border-t border-amber-800 px-4 py-2 flex items-center justify-between text-xs">
        <div className="flex items-center space-x-6">
          <span className="text-amber-100">
            Viewing: <span className="text-amber-50 font-semibold">{selectedCase}</span>
            {selectedEvidence && <span className="text-amber-50 font-semibold"> / {selectedEvidence}</span>}
          </span>
          <span className="text-amber-100 flex items-center">
            <span className="inline-block w-2 h-2 rounded-full bg-green-400 mr-2"></span>
            CLI Active: <span className="text-amber-50 font-semibold ml-1">{activeCase}</span>
            {activeEvidence && <span className="text-amber-50 font-semibold"> / {activeEvidence}</span>}
          </span>
        </div>
        <div className="flex items-center space-x-4">
          <span className="text-amber-100">
            GPG Key: <span className="text-amber-200">alice.johnson@forensics.lab (4096R/A1B2C3D4)</span>
          </span>
          <span className="flex items-center text-green-200">
            <Check className="w-3 h-3 mr-1" />
            Signing Enabled
          </span>
        </div>
      </div>
    </div>
  );
}