'use client';

import { useState, useEffect, useRef } from 'react';
import { toast } from 'sonner';
import {
  Plus,
  Trash2,
  Search,
  Copy,
  Check,
  Loader2,
  Download,
  Upload,
  Eye,
  EyeOff,
  Sparkles,
  Hash,
  List,
  Filter,
  BarChart3,
  ChevronDown,
  ChevronUp,
  ExternalLink,
  FileText,
  Tag,
  Zap,
  RefreshCw,
  Save,
  Clock,
  X,
  FileEdit,
  BookOpen,
  Type,
  Send,
  Brain,
  PenTool,
  Layers,
  FileOutput,
  FileText as FileTextIcon,
  FileJson,
  FileCode
} from 'lucide-react';

export default function EntityExtractor() {
  // State
  const [loading, setLoading] = useState(false);
  const [extracting, setExtracting] = useState(false);
  const [generatingContent, setGeneratingContent] = useState(false);
  const [topic, setTopic] = useState('');
  const [contents, setContents] = useState(['']);
  const [headings, setHeadings] = useState(['Introduction', 'Key Concepts', 'Applications', 'Benefits', 'Challenges']);
  const [extractedData, setExtractedData] = useState(null);
  const [generatedContent, setGeneratedContent] = useState(null);
  const [copiedStates, setCopiedStates] = useState({});
  const [showRawData, setShowRawData] = useState(false);
  const [activeTab, setActiveTab] = useState('setup');
  const [history, setHistory] = useState([]);
  const [expandedHeadings, setExpandedHeadings] = useState({});
  const [expandedGeneratedContent, setExpandedGeneratedContent] = useState({});
  const [filters, setFilters] = useState({
    minRelevance: 0,
    maxRelevance: 10,
    types: []
  });
  
  const fileInputRef = useRef(null);

  // Load history from localStorage
  useEffect(() => {
    const savedHistory = localStorage.getItem('entityExtractionHistory');
    if (savedHistory) {
      try {
        setHistory(JSON.parse(savedHistory));
      } catch (e) {
        console.error('Error loading history:', e);
      }
    }
  }, []);

  // Save to history
  const saveToHistory = (data) => {
    const newHistoryItem = {
      id: Date.now(),
      topic,
      timestamp: new Date().toISOString(),
      headingsCount: headings.filter(h => h.trim()).length,
      contentCount: contents.filter(c => c.trim()).length,
      extractedData: data
    };
    
    const updatedHistory = [newHistoryItem, ...history.slice(0, 9)];
    setHistory(updatedHistory);
    localStorage.setItem('entityExtractionHistory', JSON.stringify(updatedHistory));
  };

  // Add content field
  const addContentField = () => {
    setContents([...contents, '']);
  };

  // Remove content field
  const removeContentField = (index) => {
    if (contents.length > 1) {
      const newContents = [...contents];
      newContents.splice(index, 1);
      setContents(newContents);
    }
  };

  // Update content field
  const updateContent = (index, value) => {
    const newContents = [...contents];
    newContents[index] = value;
    setContents(newContents);
  };

  // Add heading field
  const addHeadingField = () => {
    setHeadings([...headings, '']);
  };

  // Remove heading field
  const removeHeadingField = (index) => {
    if (headings.length > 1) {
      const newHeadings = [...headings];
      newHeadings.splice(index, 1);
      setHeadings(newHeadings);
    }
  };

  // Update heading field
  const updateHeading = (index, value) => {
    const newHeadings = [...headings];
    newHeadings[index] = value;
    setHeadings(newHeadings);
  };

  // Toggle heading expansion
  const toggleHeadingExpansion = (heading) => {
    setExpandedHeadings(prev => ({
      ...prev,
      [heading]: !prev[heading]
    }));
  };

  // Toggle generated content expansion
  const toggleGeneratedContentExpansion = (heading) => {
    setExpandedGeneratedContent(prev => ({
      ...prev,
      [heading]: !prev[heading]
    }));
  };

  // Handle file upload
  const handleFileUpload = (event) => {
    const file = event.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = (e) => {
      const content = e.target.result;
      // Add as new content field
      setContents(prev => [...prev, content]);
      toast.success(`File "${file.name}" uploaded successfully`);
    };
    reader.readAsText(file);
  };

  // Extract entities
  const extractEntities = async () => {
    // Validation
    if (!topic.trim()) {
      toast.error('Please enter a topic');
      return;
    }

    const validContents = contents.filter(c => c.trim());
    if (validContents.length === 0) {
      toast.error('Please add at least one content source');
      return;
    }

    const validHeadings = headings.filter(h => h.trim());
    if (validHeadings.length === 0) {
      toast.error('Please add at least one heading');
      return;
    }

    setExtracting(true);
    setExtractedData(null);
    setGeneratedContent(null);
    setExpandedHeadings({});
    setExpandedGeneratedContent({});

    try {
      const response = await fetch('/api/internal/extract-entities', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          topic: topic.trim(),
          contents: validContents,
          headings: validHeadings,
        }),
      });

      const data = await response.json();
      
      if (data.success) {
        setExtractedData(data.data);
        saveToHistory(data.data);
        setActiveTab('results');
        toast.success(`Successfully extracted ${data.data.totalEntities || 'many'} entities!`);
      } else {
        toast.error(data.error || 'Extraction failed');
      }
    } catch (error) {
      console.error('Error extracting entities:', error);
      toast.error(`Error: ${error.message}`);
    } finally {
      setExtracting(false);
    }
  };

  // Generate complete content for all headings
  const generateCompleteContent = async () => {
    if (!extractedData) {
      toast.error('Please extract entities first');
      return;
    }

    setGeneratingContent(true);
    setGeneratedContent(null);

    try {
      const response = await fetch('/api/internal/extract-entities/generate-content', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          topic: extractedData.originalTopic || topic,
          entitiesByHeading: extractedData.entitiesByHeading,
          headings: extractedData.originalHeadings || headings.filter(h => h.trim()),
          originalContents: extractedData.originalContents || contents.filter(c => c.trim()),
        }),
      });

      const data = await response.json();
      
      if (data.success) {
        setGeneratedContent(data.data);
        toast.success(`Generated complete content with ${data.data.totalSections} sections!`);
      } else {
        toast.error(data.error || 'Content generation failed');
      }
    } catch (error) {
      console.error('Error generating content:', error);
      toast.error(`Error: ${error.message}`);
    } finally {
      setGeneratingContent(false);
    }
  };

  // Copy to clipboard
  const copyToClipboard = async (text, section) => {
    try {
      await navigator.clipboard.writeText(text);
      setCopiedStates({ ...copiedStates, [section]: true });
      toast.success('Copied to clipboard!');
      
      setTimeout(() => {
        setCopiedStates({ ...copiedStates, [section]: false });
      }, 2000);
    } catch (error) {
      toast.error('Failed to copy');
    }
  };

  // Export generated content as document
  const exportGeneratedContent = (format = 'markdown') => {
    if (!generatedContent?.generatedContents) {
      toast.error('No generated content to export');
      return;
    }

    let content = '';
    let filename = '';
    let mimeType = '';

    if (format === 'markdown') {
      content = `# ${extractedData?.originalTopic || topic}\n\n`;
      content += `*Generated from extracted entities on ${new Date().toLocaleDateString()}*\n\n`;
      content += `**Summary:** ${extractedData?.summary || 'No summary available'}\n\n`;
      content += `---\n\n`;

      Object.entries(generatedContent.generatedContents).forEach(([heading, sectionContent]) => {
        content += `## ${heading}\n\n`;
        content += `${sectionContent}\n\n`;
        content += `---\n\n`;
      });

      filename = `document-${topic.toLowerCase().replace(/[^a-z0-9]/g, '-')}-${Date.now()}.md`;
      mimeType = 'text/markdown;charset=utf-8';
      
      toast.success('Exported as Markdown document');
    } else if (format === 'html') {
      content = `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${extractedData?.originalTopic || topic}</title>
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; max-width: 800px; margin: 0 auto; padding: 20px; }
        h1 { color: #333; border-bottom: 2px solid #4F46E5; padding-bottom: 10px; }
        h2 { color: #4F46E5; margin-top: 30px; }
        .summary { background: #f0f9ff; padding: 15px; border-radius: 8px; margin: 20px 0; }
        .meta { color: #666; font-size: 0.9em; }
        .section { margin-bottom: 40px; }
    </style>
</head>
<body>
    <h1>${extractedData?.originalTopic || topic}</h1>
    <div class="meta">Generated from extracted entities on ${new Date().toLocaleDateString()}</div>
    
    <div class="summary">
        <strong>Summary:</strong> ${extractedData?.summary || 'No summary available'}
    </div>`;

      Object.entries(generatedContent.generatedContents).forEach(([heading, sectionContent]) => {
        content += `
    <div class="section">
        <h2>${heading}</h2>
        <div>${sectionContent.replace(/\n/g, '<br>')}</div>
    </div>`;
      });

      content += `
</body>
</html>`;

      filename = `document-${topic.toLowerCase().replace(/[^a-z0-9]/g, '-')}-${Date.now()}.html`;
      mimeType = 'text/html;charset=utf-8';
      
      toast.success('Exported as HTML document');
    }

    const blob = new Blob([content], { type: mimeType });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.setAttribute('href', url);
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  };

  // Export as JSON
  const exportAsJSON = () => {
    if (!extractedData) return;
    
    const data = {
      topic,
      headings: headings.filter(h => h.trim()),
      contents: contents.filter(c => c.trim()),
      extractedData,
      generatedContent,
      exportedAt: new Date().toISOString()
    };
    
    const dataStr = JSON.stringify(data, null, 2);
    const dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(dataStr);
    
    const exportName = `entities-${topic.toLowerCase().replace(/[^a-z0-9]/g, '-')}-${Date.now()}.json`;
    
    const link = document.createElement('a');
    link.setAttribute('href', dataUri);
    link.setAttribute('download', exportName);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    toast.success('Exported as JSON file');
  };

  // Export as CSV
  const exportAsCSV = () => {
    if (!extractedData?.entitiesByHeading) return;
    
    let csvContent = "Heading,Entity,Context,Source,Relevance,Type\n";
    
    Object.entries(extractedData.entitiesByHeading).forEach(([heading, entities]) => {
      entities.forEach(entity => {
        const row = [
          `"${heading}"`,
          `"${entity.entity.replace(/"/g, '""')}"`,
          `"${(entity.context || '').replace(/"/g, '""')}"`,
          `"${entity.source || ''}"`,
          entity.relevance || 0,
          `"${entity.type || ''}"`
        ].join(',');
        csvContent += row + '\n';
      });
    });
    
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.setAttribute('href', url);
    link.setAttribute('download', `entities-${topic.toLowerCase().replace(/[^a-z0-9]/g, '-')}-${Date.now()}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
    
    toast.success('Exported as CSV file');
  };

  // Reset form
  const resetForm = () => {
    setTopic('');
    setContents(['']);
    setHeadings(['Introduction', 'Key Concepts', 'Applications', 'Benefits', 'Challenges']);
    setExtractedData(null);
    setGeneratedContent(null);
    setActiveTab('setup');
    toast.info('Form reset to default');
  };

  // Load from history
  const loadFromHistory = (item) => {
    setTopic(item.topic);
    setContents(item.extractedData.originalContents || ['']);
    setHeadings(item.extractedData.originalHeadings || ['']);
    setExtractedData(item.extractedData);
    setGeneratedContent(null);
    setActiveTab('results');
    toast.success('Loaded from history');
  };

  // Clear history
  const clearHistory = () => {
    setHistory([]);
    localStorage.removeItem('entityExtractionHistory');
    toast.success('History cleared');
  };

  // Get entity type counts
  const getEntityTypeCounts = () => {
    if (!extractedData?.entitiesByHeading) return {};
    
    const typeCounts = {};
    Object.values(extractedData.entitiesByHeading).forEach(entities => {
      entities.forEach(entity => {
        const type = entity.type || 'Unknown';
        typeCounts[type] = (typeCounts[type] || 0) + 1;
      });
    });
    
    return typeCounts;
  };

  // Get filtered entities
  const getFilteredEntities = () => {
    if (!extractedData?.entitiesByHeading) return {};
    
    const filtered = {};
    Object.entries(extractedData.entitiesByHeading).forEach(([heading, entities]) => {
      filtered[heading] = entities.filter(entity => {
        const relevance = entity.relevance || 0;
        return relevance >= filters.minRelevance && relevance <= filters.maxRelevance;
      });
    });
    
    return filtered;
  };

  // Format date
  const formatDate = (dateString) => {
    return new Date(dateString).toLocaleString('en-US', {
      month: 'short',
      day: 'numeric',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  // Calculate content statistics
  const calculateContentStats = () => {
    const validContents = contents.filter(c => c.trim());
    const totalChars = validContents.reduce((sum, c) => sum + c.length, 0);
    const totalWords = validContents.reduce((sum, c) => sum + c.split(/\s+/).filter(w => w).length, 0);
    
    return {
      sources: validContents.length,
      characters: totalChars,
      words: totalWords,
      avgWords: Math.round(totalWords / validContents.length) || 0
    };
  };

  // Calculate generated content statistics
  const calculateGeneratedContentStats = () => {
    if (!generatedContent?.generatedContents) return { sections: 0, totalWords: 0, avgWords: 0 };
    
    const sections = Object.keys(generatedContent.generatedContents).length;
    const totalWords = Object.values(generatedContent.generatedContents).reduce((sum, content) => {
      return sum + content.split(/\s+/).filter(w => w).length;
    }, 0);
    
    return {
      sections,
      totalWords,
      avgWords: Math.round(totalWords / sections) || 0
    };
  };

  // Get all generated content as single text
  const getAllGeneratedContent = () => {
    if (!generatedContent?.generatedContents) return '';
    
    let content = `# ${extractedData?.originalTopic || topic}\n\n`;
    content += `*Generated from extracted entities on ${formatDate(generatedContent.timestamp)}*\n\n`;
    
    Object.entries(generatedContent.generatedContents).forEach(([heading, sectionContent]) => {
      content += `## ${heading}\n\n`;
      content += `${sectionContent}\n\n`;
    });
    
    return content;
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 via-white to-gray-100 p-4 md:p-8">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="mb-8 text-center">
          <div className="flex items-center justify-center gap-3 mb-4">
            <div className="p-3 bg-gradient-to-r from-blue-500 via-purple-500 to-pink-500 rounded-xl shadow-lg">
              <Sparkles className="h-8 w-8 text-white" />
            </div>
            <div>
              <h1 className="text-3xl md:text-4xl font-bold bg-gradient-to-r from-blue-600 via-purple-600 to-pink-600 bg-clip-text text-transparent">
                AI Entity Extractor & Content Generator
              </h1>
              <p className="text-gray-600 mt-2">
                Extract entities and generate complete content using DeepSeek AI
              </p>
            </div>
          </div>
        </div>

        {/* Stats Bar */}
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
          <div className="bg-white rounded-lg p-4 shadow border">
            <div className="text-sm text-gray-500">Content Sources</div>
            <div className="text-2xl font-bold text-blue-600">{calculateContentStats().sources}</div>
          </div>
          <div className="bg-white rounded-lg p-4 shadow border">
            <div className="text-sm text-gray-500">Total Words</div>
            <div className="text-2xl font-bold text-purple-600">{calculateContentStats().words.toLocaleString()}</div>
          </div>
          <div className="bg-white rounded-lg p-4 shadow border">
            <div className="text-sm text-gray-500">Headings</div>
            <div className="text-2xl font-bold text-pink-600">{headings.filter(h => h.trim()).length}</div>
          </div>
          <div className="bg-white rounded-lg p-4 shadow border">
            <div className="text-sm text-gray-500">Generated Words</div>
            <div className="text-2xl font-bold text-green-600">
              {calculateGeneratedContentStats().totalWords.toLocaleString() || '0'}
            </div>
          </div>
        </div>

        {/* Tabs Navigation */}
        <div className="flex flex-wrap gap-2 mb-8">
          <button
            onClick={() => setActiveTab('setup')}
            className={`px-5 py-2.5 rounded-lg font-medium transition-all flex items-center gap-2 ${
              activeTab === 'setup' 
                ? 'bg-gradient-to-r from-blue-500 to-purple-500 text-white shadow-lg' 
                : 'bg-white text-gray-700 hover:bg-gray-50 border shadow-sm'
            }`}
          >
            <FileText size={18} />
            Setup
          </button>
          <button
            onClick={() => setActiveTab('results')}
            className={`px-5 py-2.5 rounded-lg font-medium transition-all flex items-center gap-2 ${
              activeTab === 'results' 
                ? 'bg-gradient-to-r from-blue-500 to-purple-500 text-white shadow-lg' 
                : 'bg-white text-gray-700 hover:bg-gray-50 border shadow-sm'
            }`}
            disabled={!extractedData}
          >
            <BarChart3 size={18} />
            Results {extractedData && <span className="bg-white text-blue-600 text-xs px-2 py-0.5 rounded-full">✓</span>}
          </button>
          <button
            onClick={() => setActiveTab('history')}
            className={`px-5 py-2.5 rounded-lg font-medium transition-all flex items-center gap-2 ${
              activeTab === 'history' 
                ? 'bg-gradient-to-r from-blue-500 to-purple-500 text-white shadow-lg' 
                : 'bg-white text-gray-700 hover:bg-gray-50 border shadow-sm'
            }`}
          >
            <Clock size={18} />
            History <span className="bg-gray-200 text-gray-700 text-xs px-2 py-0.5 rounded-full">{history.length}</span>
          </button>
        </div>

        {/* Setup Tab */}
        {activeTab === 'setup' && (
          <div className="space-y-8">
            {/* Topic Card */}
            <div className="bg-white rounded-xl p-6 shadow-lg border">
              <div className="flex items-center gap-3 mb-6">
                <div className="p-2 bg-blue-100 rounded-lg">
                  <Hash className="h-5 w-5 text-blue-600" />
                </div>
                <div>
                  <h2 className="text-xl font-bold text-gray-800">Topic</h2>
                  <p className="text-sm text-gray-600">What is the main subject you want to analyze?</p>
                </div>
              </div>
              <input
                type="text"
                value={topic}
                onChange={(e) => setTopic(e.target.value)}
                placeholder="e.g., Artificial Intelligence in Healthcare, Renewable Energy Trends, Digital Marketing Strategies"
                className="w-full p-4 text-lg border-2 border-gray-200 rounded-lg focus:border-blue-500 focus:ring-4 focus:ring-blue-100 focus:outline-none transition-all"
              />
            </div>

            {/* Headings Card */}
            <div className="bg-white rounded-xl p-6 shadow-lg border">
              <div className="flex items-center justify-between mb-6">
                <div className="flex items-center gap-3">
                  <div className="p-2 bg-purple-100 rounded-lg">
                    <List className="h-5 w-5 text-purple-600" />
                  </div>
                  <div>
                    <h2 className="text-xl font-bold text-gray-800">Headings for Organization</h2>
                    <p className="text-sm text-gray-600">Categories to organize extracted entities</p>
                  </div>
                </div>
                <button
                  type="button"
                  onClick={addHeadingField}
                  className="px-4 py-2 bg-gradient-to-r from-purple-500 to-pink-500 text-white rounded-lg hover:opacity-90 transition-all flex items-center gap-2"
                >
                  <Plus size={18} /> Add Heading
                </button>
              </div>
              
              <div className="space-y-4">
                {headings.map((heading, index) => (
                  <div key={index} className="flex gap-3 items-center group">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-1">
                        <span className="text-sm font-medium text-gray-500">Heading {index + 1}</span>
                      </div>
                      <input
                        type="text"
                        value={heading}
                        onChange={(e) => updateHeading(index, e.target.value)}
                        placeholder={`e.g., ${['Key Technologies', 'Applications', 'Benefits', 'Challenges', 'Future Trends'][index] || 'Category Name'}`}
                        className="w-full p-3 border-2 border-gray-200 rounded-lg focus:border-purple-500 focus:ring-4 focus:ring-purple-100 focus:outline-none transition-all"
                      />
                    </div>
                    {headings.length > 1 && (
                      <button
                        type="button"
                        onClick={() => removeHeadingField(index)}
                        className="p-3 text-red-500 hover:bg-red-50 rounded-lg transition-colors self-end mb-1"
                        title="Remove heading"
                      >
                        <Trash2 className="h-4 w-4" />
                      </button>
                    )}
                  </div>
                ))}
              </div>
              
              <div className="mt-6 p-4 bg-gray-50 rounded-lg">
                <p className="text-sm text-gray-600">
                  <span className="font-medium">Tip:</span> Create clear, distinct headings that cover different aspects of your topic.
                  AI will organize all extracted entities under these headings.
                </p>
              </div>
            </div>

            {/* Content Sources Card */}
            <div className="bg-white rounded-xl p-6 shadow-lg border">
              <div className="flex items-center justify-between mb-6">
                <div className="flex items-center gap-3">
                  <div className="p-2 bg-green-100 rounded-lg">
                    <FileText className="h-5 w-5 text-green-600" />
                  </div>
                  <div>
                    <h2 className="text-xl font-bold text-gray-800">Content Sources</h2>
                    <p className="text-sm text-gray-600">Paste content from articles, documents, or upload files</p>
                  </div>
                </div>
                <div className="flex gap-2">
                  <button
                    type="button"
                    onClick={() => fileInputRef.current?.click()}
                    className="px-4 py-2 border-2 border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-all flex items-center gap-2"
                  >
                    <Upload size={18} /> Upload File
                  </button>
                  <button
                    type="button"
                    onClick={addContentField}
                    className="px-4 py-2 bg-gradient-to-r from-green-500 to-blue-500 text-white rounded-lg hover:opacity-90 transition-all flex items-center gap-2"
                  >
                    <Plus size={18} /> Add Source
                  </button>
                </div>
              </div>
              
              <input
                type="file"
                ref={fileInputRef}
                onChange={handleFileUpload}
                accept=".txt,.md,.csv,.json,.html"
                className="hidden"
              />
              
              <div className="space-y-6">
                {contents.map((content, index) => (
                  <div key={index} className="space-y-2">
                    <div className="flex items-center justify-between">
                      <label className="text-sm font-medium text-gray-700">
                        Content Source {index + 1}
                      </label>
                      {contents.length > 1 && (
                        <button
                          type="button"
                          onClick={() => removeContentField(index)}
                          className="text-sm text-red-500 hover:text-red-700 flex items-center gap-1"
                        >
                          <Trash2 className="h-3 w-3" /> Remove
                        </button>
                      )}
                    </div>
                    <textarea
                      value={content}
                      onChange={(e) => updateContent(index, e.target.value)}
                      placeholder={`Paste your content here... You can paste articles, research papers, documents, or any text content.

Example content:
The rapid advancement of artificial intelligence has transformed various industries. Machine learning algorithms can now process vast amounts of data to identify patterns and make predictions with remarkable accuracy.

In healthcare, AI applications include diagnostic tools that analyze medical images, predictive analytics for patient outcomes, and personalized treatment recommendations based on genetic data.

Key benefits include improved diagnostic accuracy, reduced operational costs, and enhanced patient care through continuous monitoring and early intervention systems.`}
                      rows="8"
                      className="w-full p-4 border-2 border-gray-200 rounded-lg focus:border-green-500 focus:ring-4 focus:ring-green-100 focus:outline-none transition-all resize-y font-mono text-sm"
                    />
                    <div className="flex justify-between text-xs text-gray-500">
                      <span>{content.length} characters</span>
                      <span>{content.split(/\s+/).filter(w => w).length} words</span>
                    </div>
                  </div>
                ))}
              </div>

              {/* Action Buttons */}
              <div className="mt-8 pt-6 border-t border-gray-200">
                <div className="flex flex-wrap gap-4 justify-between items-center">
                  <div className="text-sm text-gray-600">
                    <p>Ready to extract entities from {contents.filter(c => c.trim()).length} source(s)</p>
                  </div>
                  
                  <div className="flex flex-wrap gap-3">
                    <button
                      type="button"
                      onClick={resetForm}
                      className="px-5 py-2.5 border-2 border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 font-medium transition-all flex items-center gap-2"
                    >
                      <X size={18} /> Reset All
                    </button>
                    
                    <button
                      type="button"
                      onClick={extractEntities}
                      disabled={extracting || !topic.trim() || !contents.some(c => c.trim()) || !headings.some(h => h.trim())}
                      className="px-6 py-2.5 bg-gradient-to-r from-blue-600 to-purple-600 text-white rounded-lg hover:opacity-90 font-medium transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2 shadow-lg"
                    >
                      {extracting ? (
                        <>
                          <Loader2 className="h-4 w-4 animate-spin" />
                          Processing with AI...
                        </>
                      ) : (
                        <>
                          <Zap className="h-4 w-4" />
                          Extract Entities Now
                        </>
                      )}
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Results Tab */}
        {activeTab === 'results' && extractedData && (
          <div className="space-y-8">
            {/* Results Header */}
            <div className="bg-white rounded-xl p-6 shadow-lg border">
              <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-6">
                <div>
                  <h2 className="text-2xl font-bold text-gray-800">
                    Extracted Entities: {topic}
                  </h2>
                  <div className="flex items-center gap-4 mt-2 text-sm text-gray-600">
                    <span className="flex items-center gap-1">
                      <Clock size={14} />
                      {formatDate(extractedData.timestamp)}
                    </span>
                    <span>•</span>
                    <span>Processed in {extractedData.processingTime}s</span>
                    {extractedData.isDemoData && (
                      <span className="bg-yellow-100 text-yellow-800 text-xs px-2 py-1 rounded-full">
                        Demo Data
                      </span>
                    )}
                  </div>
                </div>
                
                <div className="flex flex-wrap gap-2">
                  <button
                    onClick={exportAsJSON}
                    className="px-4 py-2 bg-gradient-to-r from-blue-500 to-cyan-500 text-white rounded-lg hover:opacity-90 flex items-center gap-2"
                  >
                    <Download size={16} /> JSON
                  </button>
                  <button
                    onClick={exportAsCSV}
                    className="px-4 py-2 bg-gradient-to-r from-green-500 to-emerald-500 text-white rounded-lg hover:opacity-90 flex items-center gap-2"
                  >
                    <Download size={16} /> CSV
                  </button>
                  <button
                    onClick={() => setShowRawData(!showRawData)}
                    className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 flex items-center gap-2"
                  >
                    {showRawData ? <EyeOff size={16} /> : <Eye size={16} />}
                    Raw Data
                  </button>
                </div>
              </div>
              
              {/* Content Generation Section */}
              <div className="mb-6 p-5 bg-gradient-to-r from-blue-50 to-purple-50 border border-blue-200 rounded-lg">
                <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                  <div className="flex items-center gap-3">
                    <div className="p-2 bg-gradient-to-r from-blue-500 to-purple-500 rounded-lg">
                      <PenTool className="h-5 w-5 text-white" />
                    </div>
                    <div>
                      <h3 className="font-bold text-lg text-gray-800">Content Generation</h3>
                      <p className="text-sm text-gray-600">
                        Generate complete content for all headings based on extracted entities
                      </p>
                    </div>
                  </div>
                  
                  <div className="flex flex-wrap gap-2">
                    {generatedContent && (
                      <>
                        <div className="flex gap-2">
                          <button
                            onClick={() => exportGeneratedContent('markdown')}
                            className="px-4 py-2 bg-gradient-to-r from-green-500 to-emerald-500 text-white rounded-lg hover:opacity-90 flex items-center gap-2"
                          >
                            <FileTextIcon size={16} /> Markdown
                          </button>
                          <button
                            onClick={() => exportGeneratedContent('html')}
                            className="px-4 py-2 bg-gradient-to-r from-orange-500 to-red-500 text-white rounded-lg hover:opacity-90 flex items-center gap-2"
                          >
                            <FileCode size={16} /> HTML
                          </button>
                          <button
                            onClick={() => copyToClipboard(getAllGeneratedContent(), 'all-content')}
                            className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 flex items-center gap-2"
                          >
                            {copiedStates['all-content'] ? <Check size={16} /> : <Copy size={16} />}
                            {copiedStates['all-content'] ? 'Copied!' : 'Copy All'}
                          </button>
                        </div>
                      </>
                    )}
                    <button
                      onClick={generateCompleteContent}
                      disabled={generatingContent}
                      className="px-5 py-2.5 bg-gradient-to-r from-blue-600 to-purple-600 text-white rounded-lg hover:opacity-90 font-medium transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2 shadow-lg"
                    >
                      {generatingContent ? (
                        <>
                          <Loader2 className="h-4 w-4 animate-spin" />
                          Generating Complete Content...
                        </>
                      ) : generatedContent ? (
                        <>
                          <RefreshCw size={18} />
                          Regenerate Content
                        </>
                      ) : (
                        <>
                          <Brain className="h-4 w-4" />
                          Generate Complete Content
                        </>
                      )}
                    </button>
                  </div>
                </div>
                
                {generatedContent && (
                  <div className="mt-4 p-4 bg-white rounded-lg border border-green-200">
                    <div className="flex items-center gap-3">
                      <div className="p-2 bg-green-100 rounded-lg">
                        <Check className="h-4 w-4 text-green-600" />
                      </div>
                      <div>
                        <div className="font-medium text-gray-800">Content Generation Complete!</div>
                        <div className="text-sm text-gray-600">
                          Generated {generatedContent.totalSections} sections with {calculateGeneratedContentStats().totalWords} total words in {generatedContent.processingTime}s
                          {generatedContent.isDemoContent && ' (Demo Content)'}
                        </div>
                      </div>
                    </div>
                  </div>
                )}
              </div>
              
              {/* Summary */}
              {extractedData.summary && (
                <div className="mb-6 p-4 bg-blue-50 border border-blue-200 rounded-lg">
                  <h3 className="font-semibold text-blue-800 mb-2 flex items-center gap-2">
                    <Sparkles size={16} />
                    AI Summary
                  </h3>
                  <p className="text-blue-700">{extractedData.summary}</p>
                </div>
              )}
              
              {/* Stats Grid */}
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
                <div className="bg-gradient-to-r from-blue-50 to-blue-100 p-4 rounded-lg border border-blue-200">
                  <div className="text-sm text-blue-600 font-medium">Total Entities</div>
                  <div className="text-2xl font-bold text-blue-700">{extractedData.totalEntities?.toLocaleString() || '0'}</div>
                </div>
                <div className="bg-gradient-to-r from-purple-50 to-purple-100 p-4 rounded-lg border border-purple-200">
                  <div className="text-sm text-purple-600 font-medium">Headings</div>
                  <div className="text-2xl font-bold text-purple-700">{Object.keys(extractedData.entitiesByHeading || {}).length}</div>
                </div>
                <div className="bg-gradient-to-r from-green-50 to-green-100 p-4 rounded-lg border border-green-200">
                  <div className="text-sm text-green-600 font-medium">Avg. Relevance</div>
                  <div className="text-2xl font-bold text-green-700">
                    {(() => {
                      const allEntities = Object.values(extractedData.entitiesByHeading || {}).flat();
                      const avg = allEntities.reduce((sum, e) => sum + (e.relevance || 0), 0) / allEntities.length;
                      return avg.toFixed(1);
                    })()}
                  </div>
                </div>
                <div className="bg-gradient-to-r from-pink-50 to-pink-100 p-4 rounded-lg border border-pink-200">
                  <div className="text-sm text-pink-600 font-medium">Entity Types</div>
                  <div className="text-2xl font-bold text-pink-700">
                    {[...new Set(Object.values(extractedData.entitiesByHeading || {}).flat().map(e => e.type))].length}
                  </div>
                </div>
              </div>
            </div>

            {/* Generated Content Display */}
            {generatedContent && (
              <div className="bg-white rounded-xl shadow-lg border">
                <div className="p-6 border-b">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <div className="p-2 bg-gradient-to-r from-green-500 to-emerald-500 rounded-lg">
                        <BookOpen className="h-5 w-5 text-white" />
                      </div>
                      <div>
                        <h2 className="text-2xl font-bold text-gray-800">Generated Content</h2>
                        <p className="text-gray-600">Complete content based on extracted entities</p>
                      </div>
                    </div>
                    <button
                      onClick={() => {
                        const allExpanded = {};
                        Object.keys(generatedContent.generatedContents).forEach(heading => {
                          allExpanded[heading] = true;
                        });
                        setExpandedGeneratedContent(allExpanded);
                      }}
                      className="px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 rounded-lg"
                    >
                      Expand All
                    </button>
                  </div>
                </div>
                
                <div className="divide-y">
                  {Object.entries(generatedContent.generatedContents).map(([heading, content]) => (
                    <div key={heading} className="hover:bg-gray-50 transition-colors">
                      <div 
                        className="p-5 cursor-pointer"
                        onClick={() => toggleGeneratedContentExpansion(heading)}
                      >
                        <div className="flex items-center justify-between">
                          <div className="flex items-center gap-3">
                            <div className="p-2 bg-blue-100 rounded-lg">
                              <Type className="h-4 w-4 text-blue-600" />
                            </div>
                            <div>
                              <h3 className="font-bold text-lg text-gray-800">{heading}</h3>
                              <div className="text-sm text-gray-600">
                                {content.split(/\s+/).length} words • {Math.ceil(content.split(/\s+/).length / 200)} min read
                              </div>
                            </div>
                          </div>
                          <div className="flex items-center gap-2">
                            <button
                              onClick={(e) => {
                                e.stopPropagation();
                                copyToClipboard(content, `generated-${heading}`);
                              }}
                              className="px-3 py-1.5 bg-gray-100 text-gray-700 rounded text-sm font-medium hover:bg-gray-200 flex items-center gap-1"
                            >
                              {copiedStates[`generated-${heading}`] ? <Check size={14} /> : <Copy size={14} />}
                              {copiedStates[`generated-${heading}`] ? 'Copied!' : 'Copy'}
                            </button>
                            <button className="text-gray-400 hover:text-gray-600">
                              {expandedGeneratedContent[heading] ? <ChevronUp size={20} /> : <ChevronDown size={20} />}
                            </button>
                          </div>
                        </div>
                      </div>
                      
                      {expandedGeneratedContent[heading] && (
                        <div className="px-5 pb-5">
                          <div className="prose prose-lg max-w-none bg-gray-50 p-6 rounded-lg">
                            <div className="whitespace-pre-line leading-relaxed text-gray-700">
                              {content}
                            </div>
                          </div>
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* Loading State for Content Generation */}
            {generatingContent && (
              <div className="bg-white rounded-xl shadow-lg border p-8">
                <div className="text-center">
                  <div className="inline-block p-4 bg-gradient-to-r from-blue-50 to-purple-50 rounded-full mb-4">
                    <Loader2 className="h-12 w-12 text-blue-500 animate-spin" />
                  </div>
                  <h3 className="text-xl font-bold text-gray-800 mb-2">Generating Complete Content</h3>
                  <p className="text-gray-600 mb-6">
                    Creating content for {Object.keys(extractedData.entitiesByHeading).length} headings based on {extractedData.totalEntities} entities...
                  </p>
                  <div className="w-full bg-gray-200 rounded-full h-2 mb-2">
                    <div className="bg-gradient-to-r from-blue-500 to-purple-500 h-2 rounded-full animate-pulse"></div>
                  </div>
                  <p className="text-sm text-gray-500">This may take a minute as we generate comprehensive content for all sections</p>
                </div>
              </div>
            )}

            {/* Entities by Heading */}
            {!generatingContent && (
              <div className="space-y-6">
                <div className="flex items-center justify-between">
                  <h3 className="text-xl font-bold text-gray-800">Extracted Entities by Heading</h3>
                  <span className="text-sm text-gray-600">
                    {Object.keys(extractedData.entitiesByHeading).length} headings • {extractedData.totalEntities} entities
                  </span>
                </div>
                
                <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                  {Object.entries(getFilteredEntities()).map(([heading, entities]) => (
                    <div key={heading} className="bg-white rounded-xl shadow-lg border overflow-hidden">
                      <div 
                        className="p-5 bg-gradient-to-r from-gray-50 to-gray-100 border-b cursor-pointer hover:bg-gray-50 transition-all"
                        onClick={() => toggleHeadingExpansion(heading)}
                      >
                        <div className="flex items-center justify-between">
                          <div className="flex items-center gap-3">
                            <div className="p-2 bg-white rounded-lg border">
                              <Tag className="h-4 w-4 text-gray-600" />
                            </div>
                            <h3 className="text-lg font-bold text-gray-800">{heading}</h3>
                          </div>
                          <div className="flex items-center gap-3">
                            <span className="bg-blue-100 text-blue-700 text-sm font-medium px-3 py-1 rounded-full">
                              {entities.length} entities
                            </span>
                            <button className="text-gray-400 hover:text-gray-600">
                              {expandedHeadings[heading] ? <ChevronUp size={20} /> : <ChevronDown size={20} />}
                            </button>
                          </div>
                        </div>
                      </div>
                      
                      {(!expandedHeadings.hasOwnProperty(heading) || expandedHeadings[heading]) && (
                        <div className="p-5">
                          <div className="space-y-3 max-h-[400px] overflow-y-auto pr-2">
                            {entities.map((entity, index) => (
                              <div key={index} className="p-4 border border-gray-200 rounded-lg hover:border-blue-300 hover:shadow-sm transition-all group">
                                <div className="flex justify-between items-start mb-3">
                                  <div className="flex-1">
                                    <h4 className="font-medium text-gray-900 mb-1">{entity.entity}</h4>
                                    {entity.context && (
                                      <p className="text-sm text-gray-600 mb-2">{entity.context}</p>
                                    )}
                                  </div>
                                  <button
                                    onClick={() => copyToClipboard(entity.entity, `${heading}-${index}`)}
                                    className="ml-2 p-1.5 text-gray-400 hover:text-blue-500 transition-colors opacity-0 group-hover:opacity-100"
                                    title="Copy entity"
                                  >
                                    {copiedStates[`${heading}-${index}`] ? (
                                      <Check className="h-4 w-4 text-green-500" />
                                    ) : (
                                      <Copy className="h-4 w-4" />
                                    )}
                                  </button>
                                </div>
                                
                                <div className="flex flex-wrap gap-2">
                                  <span className={`inline-flex items-center gap-1 text-xs font-medium px-2.5 py-1 rounded-full ${
                                    entity.relevance >= 8 
                                      ? 'bg-green-100 text-green-800' 
                                      : entity.relevance >= 5 
                                      ? 'bg-yellow-100 text-yellow-800' 
                                      : 'bg-red-100 text-red-800'
                                  }`}>
                                    <span className="w-1.5 h-1.5 rounded-full bg-current"></span>
                                    {entity.relevance || 0}/10
                                  </span>
                                  
                                  {entity.type && (
                                    <span className="text-xs bg-purple-100 text-purple-700 px-2.5 py-1 rounded-full font-medium">
                                      {entity.type}
                                    </span>
                                  )}
                                  
                                  {entity.source && (
                                    <span className="text-xs bg-gray-100 text-gray-700 px-2.5 py-1 rounded-full font-medium">
                                      Source: {entity.source}
                                    </span>
                                  )}
                                </div>
                              </div>
                            ))}
                          </div>
                          
                          <div className="mt-4 pt-4 border-t border-gray-200">
                            <button
                              onClick={() => copyToClipboard(
                                entities.map(e => e.entity).join('\n'),
                                heading
                              )}
                              className="w-full py-2.5 border-2 border-gray-300 rounded-lg hover:bg-gray-50 text-sm font-medium flex items-center justify-center gap-2 transition-all"
                            >
                              {copiedStates[heading] ? (
                                <Check className="h-4 w-4 text-green-500" />
                              ) : (
                                <Copy className="h-4 w-4" />
                              )}
                              {copiedStates[heading] ? 'Copied!' : `Copy all ${entities.length} entities`}
                            </button>
                          </div>
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* Missing Categories */}
            {extractedData.missingCategories?.length > 0 && (
              <div className="bg-white rounded-xl p-6 shadow-lg border">
                <h3 className="text-lg font-bold text-gray-800 mb-4 flex items-center gap-2">
                  <Sparkles size={18} />
                  Suggested Additional Headings
                </h3>
                <div className="flex flex-wrap gap-2">
                  {extractedData.missingCategories.map((category, index) => (
                    <span key={index} className="px-3 py-2 bg-gradient-to-r from-orange-50 to-amber-50 border border-orange-200 text-orange-700 rounded-lg text-sm font-medium">
                      {category}
                    </span>
                  ))}
                </div>
              </div>
            )}

            {/* Raw Data Preview */}
            {showRawData && (
              <div className="bg-white rounded-xl p-6 shadow-lg border">
                <div className="flex items-center justify-between mb-4">
                  <h3 className="text-lg font-bold text-gray-800">Raw JSON Data</h3>
                  <button
                    onClick={() => copyToClipboard(JSON.stringify(extractedData, null, 2), 'raw-data')}
                    className="px-3 py-1.5 bg-gray-100 text-gray-700 rounded text-sm font-medium hover:bg-gray-200 flex items-center gap-2"
                  >
                    {copiedStates['raw-data'] ? <Check size={14} /> : <Copy size={14} />}
                    {copiedStates['raw-data'] ? 'Copied!' : 'Copy JSON'}
                  </button>
                </div>
                <pre className="bg-gray-900 text-gray-100 p-4 rounded-lg overflow-auto text-sm max-h-[600px]">
                  {JSON.stringify(extractedData, null, 2)}
                </pre>
              </div>
            )}

            {/* Action Buttons */}
            <div className="flex flex-wrap gap-4 justify-center pt-6">
              <button
                onClick={() => setActiveTab('setup')}
                className="px-6 py-3 border-2 border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 font-medium transition-all flex items-center gap-2"
              >
                ← Back to Setup
              </button>
              <button
                onClick={extractEntities}
                className="px-6 py-3 bg-gradient-to-r from-blue-500 to-purple-500 text-white rounded-lg hover:opacity-90 font-medium transition-all flex items-center gap-2"
              >
                <RefreshCw size={18} />
                Re-extract with Same Data
              </button>
              <button
                onClick={resetForm}
                className="px-6 py-3 bg-gradient-to-r from-red-500 to-orange-500 text-white rounded-lg hover:opacity-90 font-medium transition-all"
              >
                Start New Extraction
              </button>
            </div>
          </div>
        )}

        {/* History Tab */}
        {activeTab === 'history' && (
          <div className="bg-white rounded-xl p-6 shadow-lg border">
            <div className="flex items-center justify-between mb-6">
              <div>
                <h2 className="text-2xl font-bold text-gray-800">Extraction History</h2>
                <p className="text-gray-600">Your recent entity extractions</p>
              </div>
              {history.length > 0 && (
                <button
                  onClick={clearHistory}
                  className="px-4 py-2 text-red-600 hover:bg-red-50 rounded-lg font-medium flex items-center gap-2"
                >
                  <Trash2 size={16} />
                  Clear History
                </button>
              )}
            </div>
            
            {history.length === 0 ? (
              <div className="text-center py-12">
                <div className="text-gray-400 mb-4">
                  <Clock className="h-16 w-16 mx-auto" />
                </div>
                <h3 className="text-xl font-semibold text-gray-600 mb-2">No history yet</h3>
                <p className="text-gray-500 mb-6">Your extraction history will appear here</p>
                <button
                  onClick={() => setActiveTab('setup')}
                  className="px-5 py-2.5 bg-gradient-to-r from-blue-500 to-purple-500 text-white rounded-lg hover:opacity-90 font-medium"
                >
                  Start Your First Extraction
                </button>
              </div>
            ) : (
              <div className="space-y-4">
                {history.map((item) => (
                  <div key={item.id} className="border border-gray-200 rounded-lg p-5 hover:border-blue-300 hover:shadow-sm transition-all">
                    <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-4">
                      <div className="flex-1">
                        <h3 className="font-bold text-lg text-gray-800">{item.topic}</h3>
                        <p className="text-sm text-gray-500 mt-1">
                          {formatDate(item.timestamp)}
                        </p>
                      </div>
                      <div className="flex gap-2">
                        <button
                          onClick={() => loadFromHistory(item)}
                          className="px-4 py-2 bg-gradient-to-r from-blue-500 to-cyan-500 text-white rounded text-sm font-medium hover:opacity-90 flex items-center gap-2"
                        >
                          <RefreshCw size={14} />
                          Load
                        </button>
                      </div>
                    </div>
                    
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-4">
                      <div className="text-center p-3 bg-blue-50 rounded-lg">
                        <div className="text-sm text-blue-600">Headings</div>
                        <div className="text-lg font-bold text-blue-700">{item.headingsCount}</div>
                      </div>
                      <div className="text-center p-3 bg-purple-50 rounded-lg">
                        <div className="text-sm text-purple-600">Sources</div>
                        <div className="text-lg font-bold text-purple-700">{item.contentCount}</div>
                      </div>
                      <div className="text-center p-3 bg-green-50 rounded-lg">
                        <div className="text-sm text-green-600">Entities</div>
                        <div className="text-lg font-bold text-green-700">
                          {item.extractedData.totalEntities?.toLocaleString() || '0'}
                        </div>
                      </div>
                      <div className="text-center p-3 bg-orange-50 rounded-lg">
                        <div className="text-sm text-orange-600">Process Time</div>
                        <div className="text-lg font-bold text-orange-700">{item.extractedData.processingTime}s</div>
                      </div>
                    </div>
                    
                    <div className="flex flex-wrap gap-2">
                      {Object.keys(item.extractedData.entitiesByHeading || {}).slice(0, 5).map((heading, idx) => (
                        <span key={idx} className="bg-gray-100 text-gray-700 text-xs px-3 py-1.5 rounded-full">
                          {heading}
                        </span>
                      ))}
                      {Object.keys(item.extractedData.entitiesByHeading || {}).length > 5 && (
                        <span className="text-xs text-gray-500 px-2">
                          +{Object.keys(item.extractedData.entitiesByHeading || {}).length - 5} more
                        </span>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}