Spaces:
3SCError404
/
Paused

File size: 35,255 Bytes
2fb5a11
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2fb5a11
5eb4857
 
2fb5a11
5eb4857
 
2fb5a11
5eb4857
2fb5a11
 
 
 
 
5eb4857
 
2fb5a11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
dfcbb7c
5eb4857
 
ca7df66
 
 
 
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a27a4ab
5eb4857
 
 
 
 
 
 
 
 
 
 
dfcbb7c
 
5eb4857
5f57775
 
 
 
 
5eb4857
 
 
ca7df66
 
 
5eb4857
 
 
 
ca7df66
5eb4857
 
 
 
 
ca7df66
5eb4857
 
 
 
accf280
5eb4857
 
 
dfcbb7c
 
5eb4857
accf280
5eb4857
 
 
dfcbb7c
 
5eb4857
 
 
 
 
 
 
ca7df66
5eb4857
5f57775
 
 
 
c5e1063
 
 
5f57775
 
 
 
 
 
c5e1063
5f57775
5eb4857
 
 
 
 
dfcbb7c
 
 
 
 
 
 
 
 
 
 
 
 
5f57775
 
 
 
 
 
5eb4857
 
 
 
 
 
 
 
 
a27a4ab
5eb4857
 
 
 
 
 
 
 
a27a4ab
 
 
 
 
 
 
 
 
 
 
5eb4857
 
a27a4ab
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
a27a4ab
5eb4857
a27a4ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
 
 
a27a4ab
 
 
 
 
 
 
accf280
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f57775
 
 
904a145
5f57775
 
 
 
 
 
 
 
 
 
904a145
5f57775
 
 
 
 
 
5eb4857
 
 
 
 
 
 
 
74639ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f57775
 
 
 
 
c71c83a
5f57775
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f57775
 
 
 
 
 
 
 
 
 
 
 
 
 
8b503a7
 
 
 
 
 
 
 
 
5f57775
8b503a7
 
 
 
 
 
 
 
 
5f57775
a27a4ab
 
 
 
 
 
5f57775
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a27a4ab
5f57775
a27a4ab
5f57775
 
 
a27a4ab
5f57775
 
 
 
 
a27a4ab
5f57775
 
 
5eb4857
 
3e3b4ae
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
dfcbb7c
235f8ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dfcbb7c
 
 
 
 
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad4fe35
5eb4857
 
 
 
 
 
ad4fe35
5eb4857
 
 
 
dfcbb7c
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a27a4ab
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a27a4ab
5eb4857
 
 
 
a27a4ab
 
 
 
 
 
 
 
 
 
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a27a4ab
 
5eb4857
 
a27a4ab
 
5eb4857
 
 
a27a4ab
5eb4857
 
 
 
 
a27a4ab
5eb4857
 
 
 
 
 
 
a27a4ab
5eb4857
a27a4ab
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
import React, { useState, useEffect, useCallback } 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 { Search, Plus, X, Trash2, Edit3, ShieldCheck, Zap, Info, Radio, ChevronLeft, ChevronRight, Eye, Send, Lock, Globe, Sparkles } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { api, useAuth } from '@nexus/shared';
import mermaid from 'mermaid';
import styles from './KnowledgeBase.module.css';

// Pre-defined role groups for UI visibility
const SHRED_ROLES = ['3sc_admin', '3sc_lead', '3sc_agent'];
const EDIT_ROLES = ['3sc_admin', '3sc_lead', '3sc_agent'];

// Initialize Mermaid
mermaid.initialize({
  startOnLoad: false,
  theme: 'dark',
  securityLevel: 'loose',
  fontFamily: 'Inter, system-ui, sans-serif',
});

// Enhanced Mermaid Component
const Mermaid: React.FC<{ chart: string }> = ({ chart }) => {
  const [svg, setSvg] = useState<string>('');
  const [error, setError] = useState<string | null>(null);
  const [isRendering, setIsRendering] = useState(true);
  const [showRaw, setShowRaw] = useState(false);
  const [id] = useState(() => `mermaid-${Math.random().toString(36).substr(2, 9)}`);

  useEffect(() => {
    let isMounted = true;
    const renderChart = async () => {
      if (!chart) return;
      setIsRendering(true);
      setError(null);

      // Sanitize input to handle model artifacts or accidental wrappers
      const sanitized = chart
        .replace(/```mermaid/g, '')
        .replace(/```/g, '')
        .trim();

      try {
        // Clear previous error and SVG before re-rendering
        const { svg: renderedSvg } = await mermaid.render(id, sanitized);
        if (isMounted) {
          setSvg(renderedSvg);
          setIsRendering(false);
          setError(null);
        }
      } catch (err: any) {
        console.error("Mermaid synthesis failed:", err);
        if (isMounted) {
          setError(err.message || 'The diagram syntax is incompatible with the Nexus rendering engine.');
          setIsRendering(false);
        }
      }
    };

    renderChart();
    return () => { isMounted = false; };
  }, [chart, id]);

  if (isRendering) {
    return (
      <div className={styles.mermaidContainer}>
        <div className={styles.mermaidLoading}>
          <div className={styles.loaderPulse} />
          <span style={{ fontSize: '12px', fontWeight: 800, letterSpacing: '0.05em' }}>SYNTHESIZING ARCHITECTURE...</span>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className={styles.mermaidContainer}>
        <div className={styles.mermaidError}>
          <div className={styles.errorHeader}>
            <span className={styles.errorBadge}>SYNTHESIS FAILURE</span>
            <h4 className={styles.errorTitle}>Diagram Engine Interrupted</h4>
          </div>
          <p className={styles.errorMessage}>{error}</p>
          <button 
            type="button"
            className={styles.rawSchemaToggle} 
            onClick={() => setShowRaw(!showRaw)}
          >
            <Edit3 size={14} /> {showRaw ? 'HIDE RAW SCHEMA' : 'INSPECT RAW SCHEMA'}
          </button>
          
          <AnimatePresence>
            {showRaw && (
              <motion.div 
                initial={{ height: 0, opacity: 0 }}
                animate={{ height: 'auto', opacity: 1 }}
                exit={{ height: 0, opacity: 0 }}
                className={styles.rawSchemaBox}
              >
                {chart}
              </motion.div>
            )}
          </AnimatePresence>
        </div>
      </div>
    );
  }

  return (
    <div 
      className={styles.mermaidContainer} 
      dangerouslySetInnerHTML={{ __html: svg }} 
    />
  );
};

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 {
  workspaceId?: string;
}

export const KnowledgeBase: React.FC<KnowledgeBaseProps> = ({ workspaceId }) => {
  const { user } = useAuth();
  const canEdit = user?.role && EDIT_ROLES.includes(user.role);
  const canShred = user?.role && SHRED_ROLES.includes(user.role);

  const [articles, setArticles] = useState<Article[]>([]);
  const [categories, setCategories] = useState<string[]>(['All']);
  const [loading, setLoading] = useState(true);
  
  // Search State
  const [searchInput, setSearchInput] = useState('');
  const [activeQuery, setActiveQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('All');
  
  // Pagination State
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 4;
  
  // Dossier State
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [selectedArticle, setSelectedArticle] = useState<Article | null>(null);
  const [selectedInsight, setSelectedInsight] = useState<any | null>(null);
  const [isEditing, setIsEditing] = useState(false);
  
  // Edit Buffer
  const [editTitle, setEditTitle] = useState('');
  const [editContent, setEditContent] = useState('');
  const [editCategory, setEditCategory] = useState('');
  const [editPublished, setEditPublished] = useState(true);

  // AI Search Enhanced State
  const [suggestions, setSuggestions] = useState<string[]>([]);
  const [aiSuggestion, setAiSuggestion] = useState<string | null>(null);
  const [aiAnswer, setAiAnswer] = useState<string | null>(null);
  const [isAiSynthetic, setIsAiSynthetic] = useState(false);

  // AI Growth Center State
  const [activeTab, setActiveTab] = useState<'library' | 'growth'>('library');
  const [insights, setInsights] = useState<any[]>([]);
  const [insightsLoading, setInsightsLoading] = useState(false);

  // 1. Fetch Categories
  const fetchCategories = useCallback(async () => {
    try {
      const resp = await api.get('kb/categories/', { 
        params: { workspace_id: workspaceId } 
      });
      setCategories(['All', ...resp.data]);
    } catch (err) {
      console.error('Failed to fetch categories:', err);
    }
  }, [workspaceId]);

  // 2. Fetch Articles
  const fetchArticles = useCallback(async (query: string = '', cat: string = 'All') => {
    setLoading(true);
    try {
      const params: any = { workspace_id: workspaceId };
      if (cat !== 'All') 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 });
        setArticles(resp.data || []);
        setSuggestions([]);
        setAiSuggestion(null);
        setAiAnswer(null);
        setIsAiSynthetic(false);
      }
      setCurrentPage(1); // Reset to first page on search/filter
    } catch (err) {
      console.error('Failed to fetch articles:', err);
    } finally {
      setLoading(false);
    }
  }, [workspaceId]);

  // 3. Fetch Insights
  const fetchInsights = useCallback(async () => {
    setInsightsLoading(true);
    try {
      const resp = await api.get('kb/insights/', {
        params: { workspace_id: workspaceId }
      });
      setInsights(resp.data);
    } catch (err) {
      console.error('Failed to fetch insights:', err);
    } finally {
      setInsightsLoading(false);
    }
  }, [workspaceId]);

  useEffect(() => {
    fetchCategories();
    fetchArticles('', 'All');
  }, [fetchCategories, fetchArticles]);

  // Reactive Search Reset
  useEffect(() => {
    if (searchInput.trim() === '') {
      setActiveQuery('');
      setAiAnswer(null);
      setSuggestions([]);
      setAiSuggestion(null);
      setIsAiSynthetic(false);
      // Optional: fetchArticles('', selectedCategory); 
      // But fetchArticles is already called by the next useEffect if we change activeQuery
    }
  }, [searchInput]);

  useEffect(() => {
    if (activeTab === 'growth') {
      fetchInsights();
    }
  }, [activeTab, fetchInsights]);

  const handleSearchTrigger = (e?: React.FormEvent) => {
    if (e) e.preventDefault();
    setActiveQuery(searchInput);
    fetchArticles(searchInput, selectedCategory);
  };

  // Article Actions
  const openDossier = (article: Article) => {
    setSelectedArticle(article);
    setSelectedInsight(null);
    setEditTitle(article.title);
    setEditContent(article.content);
    setEditCategory(article.category);
    setEditPublished(article.is_published);
    setIsEditing(false);
    setDrawerOpen(true);
  };

  const openInsightDossier = (insight: any) => {
    setSelectedInsight(insight);
    setSelectedArticle(null);
    setEditTitle(insight.suggested_title);
    setEditContent(insight.suggested_content);
    setEditCategory(insight.category || 'General');
    setEditPublished(false);
    setIsEditing(false);
    setDrawerOpen(true);
  };

  const handleCreateNew = () => {
    setSelectedArticle(null);
    setSelectedInsight(null);
    setEditTitle('NEW STRATEGIC ASSET');
    setEditContent('# Technical Directive\n\nStart your documentation here...\n\n```mermaid\ngraph TD;\n    A-->B;\n```');
    setEditCategory('General');
    setEditPublished(false);
    setIsEditing(true);
    setDrawerOpen(true);
  };

  const [isSaving, setIsSaving] = useState(false);
  const [saveStatus, setSaveStatus] = useState<'idle' | 'success' | 'error'>('idle');

  const handleSaveDossier = async () => {
    setIsSaving(true);
    setSaveStatus('idle');
    
    try {
      if (selectedInsight) {
        // Save Insight Edit
        const payload = {
          suggested_title: editTitle,
          suggested_content: editContent,
          category: editCategory
        };
        const resp = await api.patch(`kb/insights/${selectedInsight.id}/`, payload);
        setInsights(prev => prev.map(i => i.id === selectedInsight.id ? { ...i, ...resp.data } : i));
        setSelectedInsight({ ...selectedInsight, ...resp.data });
      } else if (selectedArticle?.id) {
        // Save Article Update
        const payload = {
            title: editTitle,
            content: editContent,
            category: editCategory,
            is_published: editPublished
        };
        const resp = await api.patch(`kb/${selectedArticle.id}`, payload);
        setArticles(prev => prev.map(a => a.id === selectedArticle.id ? { ...a, ...resp.data } : a));
        setSelectedArticle({ ...selectedArticle, ...resp.data });
      } else {
        // Create New Article
        const payload = {
            title: editTitle,
            content: editContent,
            category: editCategory,
            is_published: editPublished
        };
        const resp = await api.post('kb/', payload);
        setArticles(prev => [resp.data, ...prev]);
        setSelectedArticle(resp.data);
      }
      setSaveStatus('success');
      setTimeout(() => {
        setIsEditing(false);
        setSaveStatus('idle');
      }, 1000);
      fetchCategories();
    } catch (err) {
      console.error('Dossier save failed:', err);
      setSaveStatus('error');
    } finally {
      setIsSaving(false);
    }
  };

  const handleDeleteArticle = async (id: string) => {
    if (!window.confirm('Retract this strategic asset from the library?')) return;
    try {
      await api.delete(`/kb/${id}`);
      setArticles(prev => prev.filter(a => a.id !== id));
      setDrawerOpen(false);
    } catch (err) {
      console.error('Retraction failed:', err);
    }
  };

  // Insight Actions
  const handleApplyInsight = async (insight: any) => {
    try {
      await api.post(`kb/insights/${insight.id}/apply/`);
      setInsights(prev => prev.filter(i => i.id !== insight.id));
      setActiveTab('library');
      fetchArticles('', selectedCategory);
    } catch (err) {
      console.error('Failed to apply insight:', err);
    }
  };

  const handleDismissInsight = async (id: string) => {
    try {
      await api.post(`kb/insights/${id}/dismiss/`);
      setInsights(prev => prev.filter(i => i.id !== id));
    } catch (err) {
      console.error('Failed to dismiss insight:', err);
    }
  };

  // Pagination Logic
  const totalPages = Math.ceil(articles.length / itemsPerPage);
  const paginatedArticles = articles.slice((currentPage - 1) * itemsPerPage, currentPage * itemsPerPage);

  return (
    <div className={styles.container}>
      <header className={styles.missionBanner}>
        <div className={styles.bannerContent}>
          <div className={styles.headerMainRow}>
            <h1>{activeTab === 'library' ? 'KNOWLEDGE LIBRARY' : 'KNOWLEDGE GROWTH'}</h1>
            
            <div className={styles.headerTabs}>
              <button 
                className={`${styles.tab} ${activeTab === 'library' ? styles.activeTab : ''}`}
                onClick={() => setActiveTab('library')}
              >
                <Globe size={14} /> LIBRARY
              </button>
              <button 
                className={`${styles.tab} ${activeTab === 'growth' ? styles.activeTab : ''}`}
                onClick={() => setActiveTab('growth')}
              >
                <Sparkles size={14} /> AI GROWTH CENTER
              </button>
            </div>
          </div>

          <p className={styles.description}>
            {activeTab === 'library' 
              ? 'Strategic intelligence gathering and architectural documentation.' 
              : 'AI-detected blindspots and documentation suggestions.'}
          </p>
          
          <form className={styles.searchControls} onSubmit={handleSearchTrigger}>
            <div className={styles.searchWrapper}>
              <Search className={styles.searchIcon} size={20} />
              <input 
                type="text" 
                placeholder="Type query and press Enter..." 
                value={searchInput}
                onChange={(e) => setSearchInput(e.target.value)}
              />
              {loading && searchInput.length > 0 && (
                <div className={styles.searchPulse}>
                  <Radio size={14} className={styles.pulseIcon} />
                  <span>NEURAL SCANNING</span>
                </div>
              )}
            </div>
            {canEdit && (
              <button type="button" className={styles.newIntelBtn} onClick={handleCreateNew}>
                <Plus size={18} /> NEW INTEL
              </button>
            )}
          </form>

          <AnimatePresence>
            {suggestions.length > 0 && (
              <motion.div 
                className={styles.suggestions}
                initial={{ opacity: 0, y: -10 }}
                animate={{ opacity: 1, y: 0 }}
              >
                <span className={styles.sLabel}>SUGGESTIONS:</span>
                {suggestions.map(s => (
                  <button 
                    key={s} 
                    className={styles.sChip}
                    onClick={() => { setSearchInput(s); setActiveQuery(s); fetchArticles(s, selectedCategory); }}
                  >
                    {s}
                  </button>
                ))}
              </motion.div>
            )}
          </AnimatePresence>
        </div>
      </header>

      <nav className={styles.categoryNav}>
        {categories.map(cat => (
          <button 
            key={cat} 
            className={`${styles.navItem} ${selectedCategory === cat ? styles.active : ''}`}
            onClick={() => { setSelectedCategory(cat); fetchArticles(activeQuery, cat); }}
          >
            {cat}
          </button>
        ))}
      </nav>

      <div className={styles.contentArea}>
        <AnimatePresence mode="wait">
          {activeTab === 'growth' ? (
             <motion.div 
               key="growth"
               className={styles.growthGrid}
               initial={{ opacity: 0, y: 20 }}
               animate={{ opacity: 1, y: 0 }}
               exit={{ opacity: 0, y: -20 }}
             >
                {insightsLoading ? (
                  <div className={styles.emptyState}>
                    <div className={styles.loadingPulse} />
                    <p>Scanning knowledge topology for gaps...</p>
                  </div>
                ) : insights.length === 0 ? (
                  <motion.div 
                    key="growth-empty" 
                    initial={{ opacity: 0, scale: 0.95 }} 
                    animate={{ opacity: 1, scale: 1 }} 
                    className={styles.emptyState}
                  >
                    <div className={styles.emptyVisual} style={{ background: 'var(--bg2)', borderRadius: '50%', padding: '40px', marginBottom: '24px' }}>
                      <ShieldCheck size={64} color="var(--primary)" />
                    </div>
                    <h3>Knowledge Equilibrium Reached</h3>
                    <p style={{ maxWidth: 450, margin: '0 auto' }}>
                      The AI Sentinel has analyzed all recent ticket resolutions and historical patterns. 
                      No critical knowledge blindspots or documentation gaps are currently detected.
                    </p>
                    <div className={styles.searchPulse} style={{ marginTop: '30px', position: 'static', transform: 'none' }}>
                       <Radio size={14} className={styles.pulseIcon} />
                       <span>CONTINUOUS MONITORING ACTIVE</span>
                    </div>
                  </motion.div>
                ) : (
                   insights.map((insight) => (
                    <motion.div key={insight.id} className={styles.insightCard} onClick={() => openInsightDossier(insight)}>
                       <div className={styles.insightHeaderRow}>
                          <span className={styles.insightType}>{insight.insight_type.replace('_', ' ')}</span>
                          <span className={styles.insightDept}>{insight.category}</span>
                       </div>
                       <div className={styles.insightContent}>
                          <h3>{insight.suggested_title}</h3>
                          <div className={styles.reasoningBox}>
                             <span className={styles.reasoningLabel}>AI REASONING</span>
                             <p className={styles.reasoningText}>{insight.reasoning}</p>
                          </div>
                       </div>

                       <div className={styles.confidenceSection}>
                          <div className={styles.confHeader}>
                             <label>CONFIDENCE LEVEL</label>
                             <span className={styles.confValue}>{Math.round(insight.confidence_score * 100)}%</span>
                          </div>
                          <div className={styles.confMeter}>
                             <div 
                               className={styles.confFill} 
                               style={{ width: `${insight.confidence_score * 100}%` }} 
                             />
                          </div>
                       </div>

                       <div className={styles.insightActions}>
                          <button 
                            className={styles.applyBtn} 
                            onClick={(e) => { e.stopPropagation(); handleApplyInsight(insight); }}
                          >
                             <Send size={14} /> DEPLOY
                          </button>
                          <button 
                            className={styles.dismissBtn}
                            onClick={(e) => { e.stopPropagation(); handleDismissInsight(insight.id); }}
                          >
                             DISMISS
                          </button>
                       </div>
                    </motion.div>
                   ))
                )}
             </motion.div>
          ) : loading && articles.length === 0 ? (
            <motion.div key="loading" initial={{ opacity: 0 }} animate={{ opacity: 1 }} className={styles.emptyState}>
              <div className={styles.loadingPulse} />
              <p>RECONNAISSANCE IN PROGRESS...</p>
            </motion.div>
          ) : articles.length === 0 ? (
            <motion.div key="empty" initial={{ opacity: 0 }} animate={{ opacity: 1 }} className={styles.emptyState}>
              <div className={styles.emptyVisual}><ShieldCheck size={64} /></div>
              <h3>Intelligence Pool Clear</h3>
              <p>No documentation found matching current operational filters.</p>
              {aiSuggestion && (
                <div className={styles.queryNudge}>
                  Did you mean: <button onClick={() => { setSearchInput(aiSuggestion); fetchArticles(aiSuggestion, selectedCategory); }}>{aiSuggestion}</button>?
                </div>
              )}
            </motion.div>
          ) : (
            <div className={styles.resultsContainer}>
              <AnimatePresence>
                {aiAnswer && (
                  <motion.div 
                    className={styles.aiSpotlight}
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    exit={{ opacity: 0, scale: 0.95 }}
                  >
                    <div className={styles.spotlightHeader}>
                      <div className={styles.spotlightBadge}>
                        <Sparkles size={14} /> AI DIRECT ANSWER
                      </div>
                      {isAiSynthetic && <span className={styles.syntheticLag}>GENERATED IN REAL-TIME</span>}
                    </div>
                    <div className={styles.answerText}>
                      <ReactMarkdown remarkPlugins={[remarkGfm]}>
                        {aiAnswer}
                      </ReactMarkdown>
                    </div>
                    <div className={styles.spotlightFooter}>
                      Based on the top documentation matches below.
                    </div>
                  </motion.div>
                )}
              </AnimatePresence>

              <motion.div 
                key="grid"
                className={styles.articlesGrid}
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
              >
              {paginatedArticles.map((article, i) => (
                <motion.div 
                  key={article.id} 
                  className={styles.articleCard}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: i * 0.05 }}
                  onClick={() => openDossier(article)}
                >
                  <div className={styles.cardHeader}>
                    <div className={styles.typeBadge}>
                      {article.match_type === 'visual' ? <Zap size={10} /> : <Info size={10} />}
                      {article.match_type?.toUpperCase() || 'DOCUMENT'}
                    </div>
                    <div className={`${styles.statusDot} ${article.is_published ? styles.live : styles.draft}`} />
                  </div>
                  
                  <div className={styles.cardBody}>
                    <span className={styles.catBadge}>{article.category}</span>
                    <h3>{article.title}</h3>
                    <p className={styles.snippet}>
                      {article.snippet || article.content.replace(/[#*`|>\-]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 140)}...
                    </p>
                  </div>

                  <div className={styles.cardFooter}>
                    <div className={styles.telemetry}>
                      <span>TELEMETRY: {new Date(article.updated_at).toLocaleDateString()}</span>
                      {article.score && <span>MATCH: {Math.round(article.score)}%</span>}
                    </div>
                  </div>
                </motion.div>
              ))}
              </motion.div>
            </div>
          )}
        </AnimatePresence>

        {totalPages > 1 && (
          <div className={styles.pagination}>
            <button 
              disabled={currentPage === 1} 
              onClick={() => setCurrentPage(p => p - 1)}
              className={styles.pageBtn}
            >
              <ChevronLeft size={18} />
            </button>
            <div className={styles.pageInfo}>
              <span>PAGE</span>
              <span className={styles.pageNum}>{currentPage}</span>
              <span>OF</span>
              <span className={styles.pageNum}>{totalPages}</span>
            </div>
            <button 
              disabled={currentPage === totalPages} 
              onClick={() => setCurrentPage(p => p + 1)}
              className={styles.pageBtn}
            >
              <ChevronRight size={18} />
            </button>
          </div>
        )}
      </div>

      {/* STRATEGIC DOSSIER DRAWER */}
      <AnimatePresence>
        {drawerOpen && (
          <>
            <motion.div 
              className={styles.drawerBackdrop}
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setDrawerOpen(false)}
            />
            <motion.div 
              className={styles.dossierDrawer}
              initial={{ x: '100%' }}
              animate={{ x: 0 }}
              exit={{ x: '100%' }}
              transition={{ type: 'spring', damping: 25, stiffness: 200 }}
            >
              <header className={styles.dossierHeader}>
                <div className={styles.dossierMeta}>
                  <div className={styles.metaTop}>
                    <span className={styles.metaLabel}>{selectedInsight ? 'AI KNOWLEDGE INSIGHT' : 'DOCUMENT INTEL'}</span>
                    <div className={styles.headerRight}>
                      {canEdit && (
                        <div className={styles.modeToggle}>
                          <button 
                            className={`${styles.modeBtn} ${!isEditing ? styles.activeMode : ''}`}
                            onClick={() => setIsEditing(false)}
                          >
                            <Eye size={14} /> VIEW
                          </button>
                          <button 
                            className={`${styles.modeBtn} ${isEditing ? styles.activeMode : ''}`}
                            onClick={() => setIsEditing(true)}
                          >
                            <Edit3 size={14} /> EDIT
                          </button>
                        </div>
                      )}
                      <button className={styles.closeDrawer} onClick={() => setDrawerOpen(false)}>
                        <X size={18} />
                      </button>
                    </div>
                  </div>
                  {isEditing ? (
                    <div className={styles.titleEditRow}>
                      <input 
                        className={styles.editTitleInput}
                        value={editTitle}
                        onChange={e => setEditTitle(e.target.value)}
                        placeholder="Article Title"
                      />
                      <button 
                        className={`${styles.deployBtn} ${saveStatus === 'success' ? styles.btnSuccess : ''} ${saveStatus === 'error' ? styles.btnError : ''}`} 
                        onClick={handleSaveDossier}
                        disabled={isSaving}
                      >
                        {isSaving ? <Radio size={14} className={styles.spin} /> : <Send size={14} />}
                        {saveStatus === 'success' ? 'UPDATED' : saveStatus === 'error' ? 'RETRY' : 'SAVE DRAFT'}
                      </button>
                    </div>
                  ) : (
                    <div className={styles.titleViewRow}>
                      <h2>{editTitle}</h2>
                      {selectedInsight ? (
                         <button className={styles.deployInsightBtn} onClick={() => handleApplyInsight(selectedInsight)}>
                            <Send size={14} /> DEPLOY TO KB
                         </button>
                      ) : (
                        <span className={`${styles.statusBadge} ${selectedArticle?.is_published ? styles.badgeLive : styles.badgeDraft}`}>
                          {selectedArticle?.is_published ? <Globe size={12} /> : <Lock size={12} />}
                          {selectedArticle?.is_published ? 'LIVE' : 'DRAFT'}
                        </span>
                      )}
                    </div>
                  )}
                </div>
              </header>

              <div className={styles.dossierBody}>
                {isEditing ? (
                  <div className={styles.editInterface}>
                    <div className={styles.compactToolbar}>
                      <div className={styles.toolbarGroup}>
                        <label>CAT</label>
                        <select value={editCategory} onChange={e => setEditCategory(e.target.value)}>
                          {categories.filter(c => c !== 'All').map(c => <option key={c} value={c}>{c}</option>)}
                          {!categories.includes('General') && <option value="General">General</option>}
                        </select>
                      </div>
                      <div className={styles.toolbarGroup}>
                        <label>VISIBILITY</label>
                        <div className={styles.miniToggles}>
                          <button 
                            className={`${styles.miniToggle} ${editPublished ? styles.activeToggle : ''}`}
                            onClick={() => setEditPublished(true)}
                          >
                            <Globe size={12} /> LIVE
                          </button>
                          <button 
                            className={`${styles.miniToggle} ${!editPublished ? styles.activeToggle : ''}`}
                            onClick={() => setEditPublished(false)}
                          >
                            <Lock size={12} /> DRAFT
                          </button>
                        </div>
                      </div>
                      {canShred && (
                        <button className={styles.miniRetract} onClick={() => selectedArticle && handleDeleteArticle(selectedArticle.id)}>
                          <Trash2 size={12} /> SHRED
                        </button>
                      )}
                    </div>
                    <div className={styles.editScrollArea}>
                      <textarea 
                        className={styles.editArea}
                        value={editContent}
                        onChange={e => setEditContent(e.target.value)}
                        placeholder="Enter strategic content in Markdown..."
                      />
                    </div>
                  </div>
                ) : (
                  <div className={styles.viewInterface}>
                    <div className={styles.telemetryBar}>
                      <div className={styles.telItem}>
                        <label>{selectedInsight ? 'CONFIDENCE' : 'AUTHOR ID'}</label>
                        <span>{selectedInsight ? `${Math.round(selectedInsight.confidence_score * 100)}%` : (selectedArticle?.author_id || 'REDACTED')}</span>
                      </div>
                      <div className={styles.telItem}>
                        <label>{selectedInsight ? 'EVIDENCE COUNT' : 'LAST SYNC'}</label>
                        <span>{selectedInsight ? selectedInsight.evidence_count : (selectedArticle ? new Date(selectedArticle.updated_at).toLocaleString() : 'N/A')}</span>
                      </div>
                      <div className={styles.telItem}>
                        <label>MATCH SCORE</label>
                        <span>{(selectedInsight ? selectedInsight.confidence_score : selectedArticle?.score) ? `${Math.round((selectedInsight ? selectedInsight.confidence_score : selectedArticle!.score) * 100)}%` : 'STATIC'}</span>
                      </div>
                    </div>
                    
                    <div className={styles.viewScrollArea}>
                      <AnimatePresence>
                        {(selectedArticle?.summary || selectedInsight?.reasoning) && (
                          <motion.div 
                            className={styles.aiInsightBox}
                            initial={{ opacity: 0, y: -20 }}
                            animate={{ opacity: 1, y: 0 }}
                          >
                            <div className={styles.insightHeader}>
                              <Sparkles size={14} className={styles.zapIcon} />
                              <span className={styles.insightLabel}>{selectedInsight ? 'AI GAP ANALYSIS' : 'AI INSIGHT'}</span>
                            </div>
                            <p className={styles.insightText}>{selectedInsight ? selectedInsight.reasoning : selectedArticle?.summary}</p>
                          </motion.div>
                        )}
                      </AnimatePresence>

                      <div className={`${styles.markdownContent} ${styles.markdownBody}`}>
                        <ReactMarkdown 
                          remarkPlugins={[remarkGfm]}
                          components={{
                            code({node, inline, className, children, ...props}: any) {
                              const match = /language-(\w+)/.exec(className || '');
                              if (!inline && match && match[1] === 'mermaid') {
                                return <Mermaid chart={String(children)} />;
                              }
                              return !inline && match ? (
                                <SyntaxHighlighter
                                  style={vscDarkPlus}
                                  language={match[1]}
                                  PreTag="div"
                                  {...props}
                                >
                                  {String(children).replace(/\n$/, '')}
                                </SyntaxHighlighter>
                              ) : (
                                <code className={className} {...props}>
                                  {children}
                                </code>
                              );
                            }
                          }}
                        >
                          {selectedArticle?.content || editContent}
                        </ReactMarkdown>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>
    </div>
  );
};