import React, { useState, useEffect, useCallback } from 'react'; import { motion, AnimatePresence } from 'framer-motion'; import { Search, ChevronLeft, ChevronRight, Sparkles, Radio, User as UserIcon, LifeBuoy, ChevronDown, Eye } from 'lucide-react'; import { api, useKnowledgeBase, useWorkspace, NexusMarkdown } from '@nexus/shared'; import styles from './KnowledgeBase.module.css'; import { Skeleton } from './Skeleton'; interface Article { id: string; title: string; content: string; category: string; author_id: string; is_published: boolean; created_at: string; updated_at: string; summary?: string; score?: number; view_count?: number; match_type?: string; snippet?: string; } interface KnowledgeBaseProps { onNewTicket?: () => void; initialArticleId?: string | null; workspaceId?: string; } export const KnowledgeBase: React.FC = ({ onNewTicket, initialArticleId, workspaceId }) => { const { workspace } = useWorkspace(); const { articles: globalArticles, categories: globalCategories, loading: globalLoading } = useKnowledgeBase(workspaceId || workspace?.id); const [localArticles, setLocalArticles] = useState([]); const [loading, setLoading] = useState(false); const [isScanning, setIsScanning] = useState(false); const [error, setError] = useState(null); const [searchInput, setSearchInput] = useState(''); const [activeQuery, setActiveQuery] = useState(''); const [selectedCategory, setSelectedCategory] = useState('All Documentation'); const [aiAnswer, setAiAnswer] = useState(null); const [isAiSynthetic, setIsAiSynthetic] = useState(false); const [aiSuggestion, setAiSuggestion] = useState(null); const [confidence, setConfidence] = useState(null); const [page, setPage] = useState(1); const ITEMS_PER_PAGE = 6; const [selectedArticle, setSelectedArticle] = useState
(null); const [sortBy, setSortBy] = useState<'newest' | 'oldest'>('newest'); const articles = (activeQuery.trim().length > 0 || selectedCategory !== 'All Documentation') ? localArticles : globalArticles; const categories = globalCategories || ['All Documentation']; const isInitialLoading = globalLoading && globalArticles.length === 0; const fetchArticles = useCallback(async (query: string = '', cat: string = 'All Documentation') => { setLoading(true); setError(null); if (query.length > 0) setIsScanning(true); try { const targetWs = workspaceId || workspace?.id; const params: any = {}; if (targetWs) params.workspace_id = targetWs; if (cat !== 'All Documentation') params.category = cat; if (query.trim().length > 0) { params.q = query; // PHASE 1: Immediate Document Retrieval (Skip Synthesis for Speed) const docsResp = await api.get('kb/search/', { params: { ...params, skip_synthesis: true } }); setLocalArticles(docsResp.data.results || []); setAiSuggestion(docsResp.data.suggestion || null); setConfidence(docsResp.data.confidence || null); // Initial state for AI setAiAnswer(null); setIsAiSynthetic(false); // PHASE 2: Background AI Synthesis (Only if query is meaningful) const isComplex = query.split(' ').length >= 2; if (isComplex) { api.get('kb/search/', { params }).then(aiResp => { if (aiResp.data.answer) { setAiAnswer(aiResp.data.answer); setIsAiSynthetic(aiResp.data.is_ai_synthetic || false); if (aiResp.data.confidence) setConfidence(aiResp.data.confidence); } }).catch(e => console.warn("AI Synthesis skipped or timed out:", e)); } } else { const resp = await api.get('kb/', { params }); const data: Article[] = resp.data || []; data.sort((a: Article, b: Article) => { const dateA = new Date(a.created_at).getTime(); const dateB = new Date(b.created_at).getTime(); return sortBy === 'newest' ? dateB - dateA : dateA - dateB; }); setLocalArticles(data); setAiAnswer(null); setConfidence(null); setIsAiSynthetic(false); setAiSuggestion(null); } setPage(1); } catch (err) { console.error('Failed to fetch articles:', err); setError('Neural connection intermittent. Please recalibrate your query.'); } finally { setLoading(false); setIsScanning(false); } }, [sortBy]); useEffect(() => { if (activeQuery.trim().length > 0 || selectedCategory !== 'All Documentation') { fetchArticles(activeQuery, selectedCategory); } }, [selectedCategory, activeQuery, fetchArticles]); useEffect(() => { if (searchInput.trim() === '') { setActiveQuery(''); setAiAnswer(null); setConfidence(null); setIsAiSynthetic(false); setAiSuggestion(null); } else if (searchInput.trim() !== activeQuery.trim()) { // Clear AI results on change to avoid stale context setAiAnswer(null); setConfidence(null); setIsAiSynthetic(false); setAiSuggestion(null); } }, [searchInput, activeQuery]); useEffect(() => { const loadInitialArticle = async () => { if (initialArticleId) { try { const resp = await api.get(`kb/${initialArticleId}/`); setSelectedArticle(resp.data); } catch (err) { console.error("Failed to fetch initial article:", err); } } }; loadInitialArticle(); }, [initialArticleId]); // Scroll to top on search/filter/pagination/drilldown useEffect(() => { const viewport = document.querySelector('.nexus-viewport'); if (viewport) viewport.scrollTop = 0; }, [activeQuery, selectedCategory, page, selectedArticle]); const handleSearchTrigger = (e?: React.FormEvent) => { if (e) e.preventDefault(); setActiveQuery(searchInput); }; const paginated = articles.slice((page - 1) * ITEMS_PER_PAGE, page * ITEMS_PER_PAGE); const totalPages = Math.ceil(articles.length / ITEMS_PER_PAGE); if (selectedArticle) { return (
{selectedArticle.category?.toUpperCase() || 'GENERAL'}
Nexus Intelligence Core
UPDATED: {new Date(selectedArticle.created_at).toLocaleDateString()}

{selectedArticle.title}

{selectedArticle.summary && (
EXECUTIVE SUMMARY

{selectedArticle.summary}

)}

Still need assistance?

Our neural-linked specialist team is standing by to resolve any operational discrepancies.

); } return (
Knowledge Base Access our comprehensive neural-indexed documentation to resolve incidents with maximum efficiency.
setSearchInput(e.target.value)} /> {isScanning && ( NEURAL SCANNING... )}
DOMAIN:
SORT:
{aiAnswer && (
SYNTHETIC INSIGHT
{isAiSynthetic && REAL-TIME ANALYSIS} {confidence && ( {Math.round(confidence * (confidence <= 1 ? 100 : 1))}% CONFIDENCE )}
Cross-referenced across {articles.length} verified documents
)}
{(loading || isScanning || isInitialLoading) ? (
{[1, 2, 3, 4, 5, 6].map(i => (
))}
) : error ? (

Connection Interrupted

{error}

) : articles.length === 0 ? (

No Intelligence Found

Our neural index yielded no direct matches for your query. Try broadening your parameters.

{aiSuggestion && (
SUGGESTED QUERY:
)}
) : ( <> {paginated.map((article, i) => ( setSelectedArticle(article)} >
{article.category?.toUpperCase() || 'GENERAL'}

{article.title}

{article.snippet ? ( {article.snippet} ) : article.summary || article.content.replace(/[#*`]/g, '').slice(0, 160) + '...'}
{new Date(article.created_at).toLocaleDateString()} {article.view_count || 0} {typeof article.score === 'number' && ( 80 ? 'var(--primary)' : 'var(--text-muted)' }}> {Math.round(article.score)}% )}
))}
{totalPages > 1 && (
INDEX: {page} / {totalPages}
)} )}
); };