import React, { useState, useEffect, useCallback, useRef } from 'react'; import ReactMarkdown from 'react-markdown'; import remarkGfm from 'remark-gfm'; import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'; import { vscDarkPlus } from 'react-syntax-highlighter/dist/esm/styles/prism'; import { motion, AnimatePresence } from 'framer-motion'; import { Search, ChevronLeft, ChevronRight, Sparkles, Radio, Clock, User as UserIcon } from 'lucide-react'; import { api } from '@nexus/shared'; import mermaid from 'mermaid'; import styles from './KnowledgeBase.module.css'; // Initialize Mermaid mermaid.initialize({ startOnLoad: true, theme: 'dark', securityLevel: 'loose', }); // Mermaid Component const Mermaid: React.FC<{ chart: string }> = ({ chart }) => { const ref = useRef(null); useEffect(() => { if (ref.current && chart) { // Robust sanitization to handle model-generated formatting artifacts const sanitized = chart .replace(/```mermaid/g, '') .replace(/```/g, '') .trim(); const id = `mermaid-${Math.random().toString(36).substr(2, 9)}`; mermaid.render(id, sanitized).then((res) => { if (ref.current) ref.current.innerHTML = res.svg; }).catch(err => { console.error("Mermaid render failed:", err); if (ref.current) { ref.current.innerHTML = `
⚠️ DIAGRAM ENGINE ERROR: Invalid Diagram Syntax
${sanitized.slice(0, 100)}...
`; } }); } }, [chart]); return
; }; 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; match_type?: string; snippet?: string; } interface KnowledgeBaseProps { onNewTicket?: () => void; } export const KnowledgeBase: React.FC = ({ onNewTicket }) => { const [articles, setArticles] = useState(() => { try { const cached = sessionStorage.getItem('nexus_kb_articles_v1'); return cached ? JSON.parse(cached) : []; } catch { return []; } }); const [categories, setCategories] = useState(() => { try { const cached = sessionStorage.getItem('nexus_kb_categories_v1'); return cached ? JSON.parse(cached) : ['All Documentation']; } catch { return ['All Documentation']; } }); const [loading, setLoading] = useState(articles.length === 0); const [isScanning, setIsScanning] = useState(false); // Search State const [searchInput, setSearchInput] = useState(''); const [activeQuery, setActiveQuery] = useState(''); const [selectedCategory, setSelectedCategory] = useState('All Documentation'); // AI Direct Answer State const [aiAnswer, setAiAnswer] = useState(null); const [isAiSynthetic, setIsAiSynthetic] = useState(false); const [suggestions, setSuggestions] = useState([]); const [aiSuggestion, setAiSuggestion] = useState(null); // UI State const [page, setPage] = useState(1); const ITEMS_PER_PAGE = 4; const [selectedArticle, setSelectedArticle] = useState
(null); const [sortBy, setSortBy] = useState<'newest' | 'oldest'>('newest'); const fetchCategories = useCallback(async () => { try { const resp = await api.get('kb/categories/'); const cats = ['All Documentation', ...resp.data]; setCategories(cats); sessionStorage.setItem('nexus_kb_categories_v1', JSON.stringify(cats)); } catch (err) { console.error('Failed to fetch categories:', err); } }, []); const fetchArticles = useCallback(async (query: string = '', cat: string = 'All Documentation') => { setLoading(true); if (query.length > 0) setIsScanning(true); try { const params: any = {}; if (cat !== 'All Documentation') params.category = cat; if (query.trim().length > 0) { params.q = query; const resp = await api.get('kb/search/', { params }); setArticles(resp.data.results || []); setSuggestions(resp.data.expanded_queries || []); setAiSuggestion(resp.data.suggestion || null); setAiAnswer(resp.data.answer || null); setIsAiSynthetic(resp.data.is_ai_synthetic || false); } else { const resp = await api.get('kb/', { params }); let data = resp.data || []; data.sort((a: any, b: any) => { const dateA = new Date(a.created_at).getTime(); const dateB = new Date(b.created_at).getTime(); return sortBy === 'newest' ? dateB - dateA : dateA - dateB; }); setArticles(data); // Cache main listing if (cat === 'All Documentation') { sessionStorage.setItem('nexus_kb_articles_v1', JSON.stringify(data)); } setSuggestions([]); setAiAnswer(null); setIsAiSynthetic(false); setAiSuggestion(null); } setPage(1); } catch (err) { console.error('Failed to fetch articles:', err); } finally { setLoading(false); setIsScanning(false); } }, [sortBy]); useEffect(() => { fetchCategories(); fetchArticles('', 'All Documentation'); }, [fetchCategories, fetchArticles]); // Reactive Search Reset useEffect(() => { if (searchInput.trim() === '') { setActiveQuery(''); if (articles.length > 0 && activeQuery !== '') { fetchArticles('', selectedCategory); } } }, [searchInput, selectedCategory, fetchArticles]); const handleSearchTrigger = (e?: React.FormEvent) => { if (e) e.preventDefault(); setActiveQuery(searchInput); fetchArticles(searchInput, selectedCategory); }; 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 || 'General'}
Admin {new Date(selectedArticle.created_at).toLocaleDateString()}

{selectedArticle.title}

{selectedArticle.summary && (
AI GENERATED SUMMARY

{selectedArticle.summary}

)}
; } return !inline && match ? ( {String(children).replace(/\n$/, '')} ) : ( {children} ); } }} > {selectedArticle.content}

Was this guide helpful?

Our tactical response teams are available 24/7 if you require further technical intelligence.

); } return (

Knowledge Base

Expert guides and troubleshooting for everything Nexus.

setSearchInput(e.target.value)} /> {isScanning && (
NEURAL SCANNING
)}
SORT BY:
{suggestions.length > 0 && ( Suggestions: {suggestions.map(s => ( ))} )}
{aiAnswer && (
AI DIRECT ANSWER
{isAiSynthetic && REAL-TIME SYNTHESIS}
{aiAnswer}
Based on the documentation below.
)}
{loading && articles.length === 0 ? (
{[1, 2, 3, 4].map(i => (
))}
) : articles.length === 0 ? (
📂

No matching intelligence

{aiSuggestion && (
Suggesting search:
)}
) : ( <> {paginated.map((article, i) => ( setSelectedArticle(article)} >
{article.category || 'General'} {article.score && ( 80 ? styles.highMatch : styles.regularMatch}`}> {Math.round(article.score)}% MATCH )}

{article.title}

{article.snippet ? ( [MATCH] {article.snippet} ) : article.summary || article.content.replace(/[#*`]/g, '').slice(0, 160) + '...'}

Published {new Date(article.created_at).toLocaleDateString()} Read Guide →
))}
{totalPages > 1 && (
Page {page} of {totalPages}
)} )}
); };