Spaces:
Paused

File size: 52,127 Bytes
a76bcb9
e79b7f5
5eb4857
f5f4a9c
1b55371
5eb4857
 
 
a4c08a4
 
ea456af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
736319b
ea456af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
736319b
 
 
 
 
 
 
 
 
 
 
5d6e6fd
5eb4857
ca7df66
5eb4857
055d291
5eb4857
055d291
5eb4857
 
a76bcb9
5eb4857
 
38aa417
ea456af
5eb4857
 
 
 
ea456af
5eb4857
 
2f50ab0
ea456af
5eb4857
 
a76bcb9
 
5eb4857
ea456af
5eb4857
 
 
 
 
 
736319b
 
 
 
1b55371
 
736319b
 
 
 
 
 
5eb4857
 
dfcbb7c
 
5eb4857
5f57775
 
a76bcb9
5f57775
a76bcb9
 
 
5f57775
5eb4857
 
 
ea456af
 
ca7df66
5eb4857
a76bcb9
ea456af
 
ca7df66
5eb4857
 
 
 
38aa417
5eb4857
a76bcb9
5eb4857
 
 
 
accf280
5eb4857
 
dfcbb7c
 
5eb4857
accf280
5eb4857
 
dfcbb7c
 
5eb4857
 
907d8c5
 
5eb4857
907d8c5
5eaa622
 
 
5eb4857
 
 
ca7df66
5eb4857
a76bcb9
 
 
ea456af
5f57775
a76bcb9
ea456af
5f57775
c5e1063
ea456af
a76bcb9
 
 
 
c5e1063
ea456af
a76bcb9
 
 
 
 
 
ea456af
a76bcb9
 
ea456af
 
 
5f57775
 
a76bcb9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f57775
5eb4857
 
 
 
 
dfcbb7c
 
 
 
 
 
 
04b3d6d
 
 
 
 
 
 
dfcbb7c
04b3d6d
dfcbb7c
5f57775
 
 
 
 
 
87d5f80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
 
 
 
 
 
 
a76bcb9
5eb4857
a27a4ab
5eb4857
 
 
 
 
 
 
 
a76bcb9
a27a4ab
 
 
 
 
 
 
 
 
 
5eb4857
 
a27a4ab
736319b
5eb4857
 
 
 
 
 
736319b
 
 
 
f530d09
 
736319b
 
f530d09
 
 
 
055d291
f530d09
 
 
055d291
736319b
 
 
f530d09
736319b
 
f530d09
50d145d
736319b
37c3bcb
 
0879c61
907d8c5
0879c61
 
 
 
 
 
37c3bcb
 
0879c61
 
 
 
f530d09
 
 
 
907d8c5
 
f530d09
055d291
736319b
055d291
736319b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
055d291
 
 
 
 
 
 
736319b
055d291
736319b
 
 
 
 
 
 
 
 
 
055d291
736319b
5eb4857
 
055d291
1b55371
 
 
 
 
 
 
5eb4857
 
3cd2dfd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
 
 
 
ea456af
5eb4857
a27a4ab
 
 
 
 
 
 
 
 
 
 
 
 
ea456af
 
 
 
a27a4ab
 
5eb4857
 
 
a27a4ab
 
ea456af
 
 
 
a27a4ab
50d145d
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
055d291
 
 
 
 
 
 
5eb4857
055d291
5eb4857
 
 
 
 
 
 
 
5f57775
a76bcb9
5f57775
904a145
5f57775
 
 
 
 
 
 
 
 
 
904a145
5f57775
 
 
 
 
 
5ec93af
 
 
 
 
 
 
5eb4857
 
 
 
 
74639ef
 
ea456af
74639ef
ea456af
74639ef
 
 
 
 
ea456af
74639ef
 
 
 
 
 
5f57775
 
 
ea456af
 
c71c83a
5f57775
ea456af
5eb4857
 
 
ea456af
 
 
5eb4857
 
 
 
 
 
 
 
 
 
 
736319b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f530d09
 
 
 
 
 
 
 
736319b
5eb4857
 
 
907d8c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
829f259
907d8c5
 
 
 
 
 
 
 
5eb4857
 
 
 
37c3bcb
5ec93af
37c3bcb
 
 
 
 
 
 
 
 
 
 
5ec93af
37c3bcb
 
 
907d8c5
37c3bcb
 
 
907d8c5
0879c61
 
 
 
37c3bcb
 
 
 
 
 
 
 
 
5eb4857
5f57775
ea456af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f57775
ea456af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b503a7
ea456af
 
 
 
38aa417
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5f57775
5eb4857
 
3e3b4ae
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
dfcbb7c
235f8ef
 
ea456af
235f8ef
02ae297
 
 
 
235f8ef
 
 
 
 
 
 
 
f5f4a9c
235f8ef
 
 
 
 
 
 
 
ea456af
dfcbb7c
 
 
 
 
ea456af
 
 
 
 
 
 
 
 
 
 
 
 
 
7a44ff2
5eaa622
7a44ff2
 
 
 
 
 
5eb4857
 
ea456af
 
 
 
3cc3ff8
ea456af
5eb4857
ea456af
 
 
3cc3ff8
ea456af
 
 
 
 
 
dfcbb7c
 
5eb4857
 
 
a76bcb9
5eb4857
ea456af
 
5eb4857
 
 
 
 
 
 
 
 
 
 
ea456af
 
5eb4857
 
 
 
 
 
 
 
37c3bcb
5eb4857
 
 
 
 
ea456af
5eb4857
 
 
 
 
 
ea456af
5eb4857
 
 
 
 
 
 
 
 
a27a4ab
5eb4857
736319b
 
 
 
 
 
 
 
 
 
1b55371
736319b
 
 
1b55371
 
 
 
 
 
 
 
 
736319b
 
 
 
 
 
 
 
 
5eb4857
ea456af
5eb4857
 
 
 
 
ea456af
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
d3c9c23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
 
 
a27a4ab
 
ea456af
 
 
a27a4ab
 
 
 
 
 
5eb4857
 
 
 
 
 
 
 
 
 
 
d3c9c23
5eb4857
 
 
 
 
 
 
ea456af
5eb4857
d3c9c23
 
5eb4857
 
 
ea456af
5eb4857
d3c9c23
 
5eb4857
 
 
 
 
3cd2dfd
 
 
 
 
 
 
 
 
 
 
5eb4857
d3c9c23
 
 
 
 
5eb4857
 
 
 
 
d3c9c23
 
 
 
 
 
ea456af
5eb4857
 
 
 
d3c9c23
5eb4857
 
 
 
 
736319b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b55371
 
 
 
 
 
 
 
 
 
 
 
 
 
 
736319b
 
 
 
 
5eb4857
736319b
 
 
 
 
 
 
 
 
 
 
04b3d6d
 
 
 
 
 
736319b
ea456af
5eb4857
 
055d291
ea456af
055d291
5eb4857
 
 
 
 
 
a27a4ab
5eb4857
a27a4ab
5eb4857
 
 
 
 
1b55371
 
 
 
 
 
 
055d291
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b55371
 
055d291
1b55371
f5f4a9c
1b55371
5eb4857
1b55371
5eb4857
736319b
5eb4857
 
736319b
 
 
 
 
 
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
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Search, Plus, X, Trash2, Edit3, ShieldCheck, Zap, Info, Radio, ChevronLeft, ChevronRight, Eye, Send, Lock, Globe, Sparkles, UploadCloud, History, RotateCcw, Clock, ChevronDown } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { api, useAuth, computeDiff, useNotification, NexusMarkdown } from '@nexus/shared';

import styles from './KnowledgeBase.module.css';

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

interface KBArticle {
  id: string;
  title: string;
  content: string;
  category: string;
  is_published: boolean;
  updated_at: string;
  author_id?: string;
  view_count: number;
  citation_count: number;
  score?: number;
  snippet?: string;
  match_type?: string;
  created_at?: string;
  summary?: string;
  version?: number;
}

interface KnowledgeBaseProps {
  workspaceId?: string;
}

interface KBInsight {
  id: string;
  insight_type: 'DEPTH_IMPROVEMENT' | 'NEW_TOPIC';
  suggested_title: string;
  suggested_content: string;
  reasoning: string;
  confidence_score: number;
  category: string;
  evidence_count: number;
}

interface KBArticleVersion {
  id: string;
  version_number: number;
  title: string;
  content: string;
  category: string;
  created_at: string;
  author_id: string;
  author_name: string;
}

// Mermaid logic moved to centralized NexusMermaid.tsx component in @nexus/shared

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

  const canShred = user?.role && SHRED_ROLES.includes(user.role);

  const [articles, setArticles] = useState<KBArticle[]>([]);
  const [categories, setCategories] = useState<string[]>(['All']);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Search State
  const [searchInput, setSearchInput] = useState('');
  const [activeQuery, setActiveQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('All');

  // Pagination State
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 6;

  // Dossier State
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [selectedArticle, setSelectedArticle] = useState<KBArticle | null>(null);
  const [selectedInsight, setSelectedInsight] = useState<KBInsight | 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);

  // Version History State
  const [showHistory, setShowHistory] = useState(false);
  const [versions, setVersions] = useState<KBArticleVersion[]>([]);
  const [versionsLoading, setVersionsLoading] = useState(false);
  const [comparingVersion, setComparingVersion] = useState<KBArticleVersion | null>(null);


  // File Upload State
  const [isDropdownOpen, setIsDropdownOpen] = useState(false);
  const [isParsingFile, setIsParsingFile] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // AI Search Enhanced State
  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<KBInsight[]>([]);
  const [insightsLoading, setInsightsLoading] = useState(false);
  const [insightsPage, setInsightsPage] = useState(0);
  const [hasMoreInsights, setHasMoreInsights] = useState(true);
  const loadingRef = useRef<HTMLDivElement>(null);

  // 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: unknown) {
      console.error('Failed to fetch categories:', err);
    }
  }, [workspaceId]);

  // 2. Fetch Articles
  const fetchArticles = useCallback(async (query: string = '', cat: string = 'All') => {
    setLoading(true);
    setError(null);
    try {
      const params: Record<string, string | undefined> = { 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 || []);
        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 || []);
        setAiSuggestion(null);
        setAiAnswer(null);
        setIsAiSynthetic(false);
      }
      setCurrentPage(1); // Reset to first page on search/filter
    } catch (err: unknown) {
      const errorObj = err as { code?: string; message?: string; response?: { data?: { detail?: string } } };
      console.error('Failed to fetch articles:', err);
      const isTimeout = errorObj.code === 'ECONNABORTED' || errorObj.message?.includes('timeout');
      setError(isTimeout 
        ? 'Neural core processing exceeded 120s deadline. High-load detected. Retrying from cache recommended.' 
        : 'Search intelligence interrupted. Regional grid may be unstable.');
    } finally {
      setLoading(false);
    }
  }, [workspaceId]);

  // 3. Fetch Insights (Paginated for Infinite Scroll)
  const fetchInsights = useCallback(async (reset: boolean = false) => {
    if (insightsLoading || (!hasMoreInsights && !reset)) return;

    setInsightsLoading(true);
    const nextPage = reset ? 0 : insightsPage;

    try {
      const resp = await api.get('kb/insights/', {
        params: {
          workspace_id: workspaceId,
          skip: nextPage * 10,
          limit: 10
        }
      });

      const newInsights = resp.data || [];
      if (reset) {
        setInsights(newInsights);
      } else {
        setInsights(prev => [...prev, ...newInsights]);
      }

      setHasMoreInsights(newInsights.length === 10);
      setInsightsPage(nextPage + 1);
    } catch (err: unknown) {
      console.error('Failed to fetch insights:', err);
    } finally {
      setInsightsLoading(false);
    }
  }, [workspaceId, insightsPage, insightsLoading, hasMoreInsights]);

  // Infinite Scroll Observer
  useEffect(() => {
    if (activeTab !== 'growth' || !hasMoreInsights) return;

    const observer = new IntersectionObserver((entries) => {
      if (entries[0].isIntersecting && !insightsLoading) {
        fetchInsights();
      }
    }, { threshold: 1.0 });

    if (loadingRef.current) {
      observer.observe(loadingRef.current);
    }

    return () => observer.disconnect();
  }, [activeTab, hasMoreInsights, insightsLoading, fetchInsights]);

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

  // Reactive Search Reset
  useEffect(() => {
    if (searchInput.trim() === '') {
      setActiveQuery('');
      setAiAnswer(null);
      setAiSuggestion(null);
      setIsAiSynthetic(false);
      // Trigger reset fetch to show all articles again
      fetchArticles('', selectedCategory);
    } else if (searchInput.trim() !== activeQuery.trim()) {
      // Clear AI results on change to avoid stale context
      setAiAnswer(null);
      setAiSuggestion(null);
      setIsAiSynthetic(false);
    }
  }, [searchInput, activeQuery, selectedCategory, fetchArticles]);

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

  // Scroll to top on search/filter/pagination
  useEffect(() => {
    const viewport = document.querySelector('.admin-content');
    if (viewport) viewport.scrollTop = 0;
  }, [activeQuery, selectedCategory, currentPage]);

  // Scroll drawer to top on article change
  useEffect(() => {
    if (drawerOpen) {
      const viewArea = document.querySelector(`.${styles.viewScrollArea}`);
      const editArea = document.querySelector(`.${styles.editScrollArea}`);
      if (viewArea) viewArea.scrollTop = 0;
      if (editArea) editArea.scrollTop = 0;
    }
  }, [selectedArticle, selectedInsight, drawerOpen]);

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

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

  const openInsightDossier = (insight: KBInsight) => {
    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);
    setShowHistory(false);
    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);
    setIsDropdownOpen(false);
  };

  const handleFileUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = event.target.files;
    if (!files || files.length === 0) return;

    setIsDropdownOpen(false);
    
    // Check for any file over 1MB
    const tooLarge = Array.from(files).find(f => f.size > 1024 * 1024);
    if (tooLarge) {
      alert(`File "${tooLarge.name}" is too large (Limit: 1MB for background ingestion).`, { type: 'error', title: 'Upload Restriction' });
      return;
    }


    setIsParsingFile(true);
    
    const formData = new FormData();
    Array.from(files).forEach(f => formData.append('files', f));

    try {
      // Transitioning to background ingestion job for stability (GAP-4 / Hardening)
      const resp = await api.post('kb/ingest/', formData, { params: { workspace_id: workspaceId } });
      
      
      if (resp.data.created_drafts && resp.data.created_drafts.length > 0) {
        // Only inject into grid if it matches current filter or 'All'
        const relevantDrafts = resp.data.created_drafts.filter((d: KBArticle) => 
          selectedCategory === 'All' || d.category === selectedCategory
        );
        
        if (relevantDrafts.length > 0) {
          setArticles(prev => [...relevantDrafts, ...prev]);
        }
      }

      // No alert needed if we have immediate drafts, the UI handles it
      if (!resp.data.created_drafts || resp.data.created_drafts.length === 0) {
        alert(resp.data.message || `${files.length} documents queued for neural ingestion.`);
      }
      
      // Auto-refresh library after a small delay to show processing articles
      setTimeout(() => fetchArticles(activeQuery, selectedCategory), 2000);
      
    } catch (err: unknown) {
      const errorObj = err as { response?: { data?: { detail?: string } } };
      console.error('Ingestion failed:', err);
      alert(errorObj.response?.data?.detail || 'Failed to initiate neural ingestion.', { type: 'error', title: 'Ingestion Failure' });
    } finally {

      setIsParsingFile(false);
      if (fileInputRef.current) fileInputRef.current.value = '';
    }
  };

  const loadVersions = async () => {
    if (!selectedArticle) return;
    setVersionsLoading(true);
    try {
      const resp = await api.get(`kb/${selectedArticle.id}/versions/`);
      setVersions(resp.data || []);
    } catch (err) {
      console.error('Failed to load version history', err);
    } finally {
      setVersionsLoading(false);
    }
  };

  const handleRestoreVersion = async (versionId: string) => {
    if (!selectedArticle) return;
    const confirmed = await confirm("Restore this version? This will overwrite the current article with this historical snapshot.", {
      title: "Restore Version",
      confirmLabel: "Restore",
      type: "warning"
    });
    if (!confirmed) return;
    try {

      const resp = await api.post(`kb/${selectedArticle.id}/restore/${versionId}/`);
      setArticles(prev => prev.map(a => a.id === selectedArticle.id ? { ...a, ...resp.data } : a));
      setSelectedArticle({ ...selectedArticle, ...resp.data });
      setEditTitle(resp.data.title);
      setEditContent(resp.data.content);
      setEditCategory(resp.data.category);
      // Reload versions to show current newly created snapshot
      await loadVersions();
    } catch (err) {
      console.error('Failed to restore version', err);
      alert('Failed to restore version.', { type: 'error', title: 'System Error' });
    }
  };


  const handleCompareVersion = (version: KBArticleVersion) => {
    setComparingVersion(version);
    setShowHistory(false);
    setIsEditing(false);
  };


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

  const handleAutoDraft = async () => {
    if (!editContent.trim()) return;
    
    setIsAutoDrafting(true);
    try {
      const resp = await api.post('kb/autodraft/', { content: editContent });
      if (resp.data.formatted_content) {
        setEditContent(resp.data.formatted_content);
        alert('Neural formatting applied successfully.', { type: 'success', title: 'Auto Draft' });
      }
    } catch (err) {
      console.error('Auto draft failed:', err);
      alert('Failed to apply neural formatting.', { type: 'error', title: 'System Error' });
    } finally {
      setIsAutoDrafting(false);
    }
  };

  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, { params: { workspace_id: workspaceId } });
        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) => {
    const confirmed = await confirm('Retract this strategic asset from the library?', {
      title: 'Retract Asset',
      confirmLabel: 'Retract',
      type: 'error',
      danger: true
    });
    if (!confirmed) 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: KBInsight) => {
    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 & Drafts Logic
  const allDrafts = articles.filter(a => !a.is_published);
  const draftsToDisplay = allDrafts;
  
  const publishedArticles = articles.filter(a => a.is_published);
  const totalPages = Math.ceil(publishedArticles.length / itemsPerPage);
  const paginatedArticles = publishedArticles.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 && (
              <div className={styles.newIntelDropdownWrapper}>
                <button 
                  type="button" 
                  className={styles.newIntelBtn} 
                  onClick={() => setIsDropdownOpen(!isDropdownOpen)}
                  disabled={isParsingFile}
                >
                  {isParsingFile ? (
                    <><Radio size={18} className={styles.pulseIcon} /> PARSING</>
                  ) : (
                    <><Plus size={18} /> NEW INTEL</>
                  )}
                </button>
                <AnimatePresence>
                  {isDropdownOpen && (
                    <motion.div 
                      className={styles.newIntelDropdown}
                      initial={{ opacity: 0, y: 10 }}
                      animate={{ opacity: 1, y: 0 }}
                      exit={{ opacity: 0, scale: 0.95 }}
                    >
                      <button type="button" onClick={handleCreateNew} className={styles.intelOption}>
                        <Edit3 size={16} /> Write Article
                        <span>Start from an empty technical directive</span>
                      </button>
                      <button type="button" onClick={() => fileInputRef.current?.click()} className={styles.intelOption}>
                        <UploadCloud size={16} /> Upload & Parse (AI)
                        <span>Convert .txt / .md into structured article</span>
                      </button>
                    </motion.div>
                  )}
                </AnimatePresence>
                  <input 
                    type="file" 
                    ref={fileInputRef} 
                    onChange={handleFileUpload} 
                    accept=".txt,.md" 
                    multiple
                    style={{ display: 'none' }} 
                  />
              </div>
            )}
          </form>

          {activeTab === 'library' && (
            <div className={styles.categoryDropdownRow} style={{ marginTop: '40px' }}>
              <div className={styles.categorySelectWrapper}>
                <span className={styles.categoryLabel}>OPERATIONAL FOCUS:</span>
                <div className={styles.customSelect}>
                  <select 
                    value={selectedCategory}
                    onChange={(e) => { 
                      setSelectedCategory(e.target.value); 
                      fetchArticles(activeQuery, e.target.value); 
                    }}
                  >
                    <option value="All">ALL DEPARTMENTS</option>
                    {categories.filter(c => c !== 'All').map(cat => (
                      <option key={cat} value={cat}>
                        {(cat || 'general').toUpperCase()}
                      </option>
                    ))}
                  </select>
                  <ChevronDown size={14} className={styles.selectIcon} />
                </div>
              </div>
            </div>
          )}
        </div>
      </header>

      <div className={styles.contentArea}>
        <AnimatePresence>
          {draftsToDisplay.length > 0 && activeTab === 'library' && (
            <motion.aside 
              className={styles.draftSidebar}
              initial={{ opacity: 0, x: -50 }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: -50 }}
            >
              <div className={styles.sidebarHeader}>
                <Clock size={16} />
                <h3>RECENT DRAFTS</h3>
              </div>
              <div className={styles.draftList}>
                {draftsToDisplay.map(draft => (
                  <div 
                    key={draft.id} 
                    className={styles.draftItem}
                    onClick={() => openDossier(draft)}
                  >
                    <div className={styles.draftTitle}>{draft.title}</div>
                    <div className={styles.draftMeta}>
                      {draft.score ? (
                        <><Eye size={10} /> VIEW EXISTING</>
                      ) : (
                        <><Zap size={10} /> READY FOR REVIEW</>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            </motion.aside>
          )}
        </AnimatePresence>

        <div className={styles.mainLibrary}>
        <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 === 'DEPTH_IMPROVEMENT' ? 'Increase in depth of article' : 'New topics'}
                        </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>PRIORITY SCORE</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>
                  )}
                  <div ref={loadingRef} style={{ height: '2px', width: '100%' }} />
                  {insightsLoading && (
                    <div className={styles.emptyState}>
                      <div className={styles.loadingPulse} />
                    </div>
                  )}
                </>
              )}
            </motion.div>
          ) : error ? (
            <motion.div key="error" initial={{ opacity: 0 }} animate={{ opacity: 1 }} className={styles.emptyState}>
              <div className={styles.emptyVisual} style={{ background: 'rgba(239, 68, 68, 0.1)' }}>
                <Info size={64} color="#ef4444" />
              </div>
              <h3 style={{ color: '#ef4444' }}>Operational Failure</h3>
              <p>{error}</p>
              <button 
                className={styles.newIntelBtn} 
                onClick={() => fetchArticles(searchInput, selectedCategory)}
                style={{ marginTop: '20px' }}
              >
                RE-INITIALIZE SCAN
              </button>
            </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: 30, filter: 'blur(10px)' }}
                    animate={{ opacity: 1, y: 0, filter: 'blur(0px)' }}
                    exit={{ opacity: 0, scale: 0.98, filter: 'blur(5px)' }}
                    transition={{ type: 'spring', damping: 25, stiffness: 120 }}
                  >
                    <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}>
                      <NexusMarkdown content={aiAnswer} />
                    </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 style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                        {typeof article.score === 'number' && !Number.isNaN(article.score) && (
                          <span className={`${styles.matchBadge} ${article.score > 80 ? styles.highMatch : styles.regularMatch}`}>
                            {Math.round(article.score)}% CONFIDENCE
                          </span>
                        )}
                        <div className={`${styles.statusDot} ${article.is_published ? styles.live : styles.draft}`} />
                      </div>
                    </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 title="Last updated"><Radio size={12} /> {article.updated_at ? new Date(article.updated_at).toLocaleDateString() : 'Just now'}</span>
                        {article.view_count > 0 && <span title="Article Views"><Eye size={12} /> {article.view_count}</span>}
                        {article.citation_count > 0 && <span title="Cited by AI"><Sparkles size={12} /> {article.citation_count}</span>}
                      </div>
                    </div>
                  </motion.div>
                ))}
              </motion.div>
            </div>
          )}
        </AnimatePresence>

        {activeTab === 'library' && 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>
    </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 && !selectedInsight && (
                        <div className={styles.modeToggle}>
                          <button
                            className={`${styles.modeBtn} ${!isEditing && !showHistory ? styles.activeMode : ''}`}
                            onClick={() => { setIsEditing(false); setShowHistory(false); }}
                          >
                            <Eye size={14} /> VIEW
                          </button>
                          <button
                            className={`${styles.modeBtn} ${!isEditing && showHistory ? styles.activeMode : ''}`}
                            onClick={() => { setIsEditing(false); setShowHistory(true); setComparingVersion(null); loadVersions(); }}
                          >
                            <History size={14} /> HISTORY
                          </button>
                          {comparingVersion && (
                            <button
                              className={`${styles.modeBtn} ${comparingVersion ? styles.activeMode : ''}`}
                              onClick={() => { setIsEditing(false); setShowHistory(false); }}
                            >
                              <Search size={14} /> DIFF v{comparingVersion.version_number}
                            </button>
                          )}

                          <button
                            className={`${styles.modeBtn} ${isEditing ? styles.activeMode : ''}`}
                            onClick={() => { setIsEditing(true); setShowHistory(false); }}
                          >
                            <Edit3 size={14} /> EDIT
                          </button>
                        </div>
                      )}
                      {canEdit && selectedInsight && (
                        <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..."
                          disabled={isAutoDrafting}
                        />
                        <button
                          className={`${styles.deployBtn} ${saveStatus === 'success' ? styles.btnSuccess : ''} ${saveStatus === 'error' ? styles.btnError : ''}`}
                          onClick={handleSaveDossier}
                          disabled={isSaving || isAutoDrafting}
                        >
                          {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)} disabled={isAutoDrafting}>
                          {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={() => !isAutoDrafting && setEditPublished(true)}
                            disabled={isAutoDrafting}
                          >
                            <Globe size={12} /> LIVE
                          </button>
                          <button
                            className={`${styles.miniToggle} ${!editPublished ? styles.activeToggle : ''}`}
                            onClick={() => !isAutoDrafting && setEditPublished(false)}
                            disabled={isAutoDrafting}
                          >
                            <Lock size={12} /> DRAFT
                          </button>
                        </div>
                      </div>
                      <div className={styles.toolbarGroup}>
                        <button 
                          className={`${styles.autoDraftBtn} ${isAutoDrafting ? styles.btnPulse : ''}`}
                          onClick={handleAutoDraft}
                          disabled={isAutoDrafting}
                          title="Apply neural formatting to content"
                        >
                          {isAutoDrafting ? <Radio size={12} className={styles.spin} /> : <Sparkles size={12} />}
                          {isAutoDrafting ? 'FORMATTING...' : 'AUTO DRAFT'}
                        </button>
                      </div>
                      {canShred && (
                        <button 
                          className={styles.miniRetract} 
                          onClick={() => selectedArticle && !isAutoDrafting && handleDeleteArticle(selectedArticle.id)}
                          disabled={isAutoDrafting}
                        >
                          <Trash2 size={12} /> SHRED
                        </button>
                      )}
                    </div>
                    <div className={styles.editScrollArea}>
                      {isAutoDrafting && (
                        <div className={styles.editorOverlay}>
                          <Radio className={styles.spin} size={32} color="var(--primary)" />
                          <span className={styles.overlayText}>Neural Formatting in Progress...</span>
                        </div>
                      )}
                      <textarea
                        className={styles.editArea}
                        value={editContent}
                        onChange={e => setEditContent(e.target.value)}
                        placeholder="Enter strategic content in Markdown..."
                        readOnly={isAutoDrafting}
                      />
                    </div>
                  </div>
                ) : (
                  <div className={styles.viewInterface}>
                    {showHistory && !isEditing && selectedArticle ? (
                      <div className={styles.historyContainer}>
                        <div className={styles.historyHeader}>
                          <History size={18} />
                          <h3>Article Version Ledger</h3>
                        </div>
                        <p className={styles.historySub}>Previous iterations automatically snapshotted upon modification.</p>
                        
                        {versionsLoading ? (
                          <div className={styles.emptyState}>
                            <div className={styles.loadingPulse} />
                          </div>
                        ) : versions.length === 0 ? (
                          <div className={styles.emptyState}>
                            <p>No historical versions found.</p>
                          </div>
                        ) : (
                          <div className={styles.timelineList}>
                            {versions.map((ver, idx) => (
                              <div key={ver.id} className={styles.timelineNode}>
                                <div className={styles.nodeLine} />
                                <div className={styles.nodeDot}>{versions.length - idx === selectedArticle.version ? '★' : ''}</div>
                                <div className={styles.nodeContent}>
                                  <div className={styles.nodeHeader}>
                                    <span className={styles.nodeVersion}>v{ver.version_number}</span>
                                    <span className={styles.nodeDate}>{new Date(ver.created_at).toLocaleString()}</span>
                                  </div>
                                  <div className={styles.nodeMeta}>
                                    <span>Author: {ver.author_name}</span>
                                    <span>Title: {ver.title}</span>
                                  </div>
                                  <div className={styles.historyActions}>
                                    <button 
                                      className={styles.restoreBtn} 
                                      onClick={() => handleRestoreVersion(ver.id)}
                                    >
                                      <RotateCcw size={14} /> RESTORE
                                    </button>
                                    <button 
                                      className={styles.compareBtn} 
                                      onClick={() => handleCompareVersion(ver)}
                                    >
                                      <Search size={14} /> COMPARE
                                    </button>
                                  </div>

                                </div>
                              </div>
                            ))}
                          </div>
                        )}
                      </div>
                    ) : (
                      <>
                        <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>
                          {!selectedInsight && (
                            <div className={styles.telItem}>
                              <label>MATCH SCORE</label>
                              <span>{selectedArticle?.score ? `${Math.round(selectedArticle.score)}%` : 'STATIC'}</span>
                            </div>
                          )}
                        </div>

                    <div className={styles.viewScrollArea}>
                      <AnimatePresence>
                        {(selectedArticle?.summary || selectedInsight?.reasoning) && !comparingVersion && (
                          <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}`}>
                        {comparingVersion ? (
                          <div className={styles.diffView}>
                            <div className={styles.diffHeader}>
                              <span>Comparing Current vs v{comparingVersion.version_number}</span>
                              <button className={styles.exitDiff} onClick={() => setComparingVersion(null)}>EXIT DIFF</button>
                            </div>
                            <div className={styles.diffLines}>
                              {(() => {
                                const diffs = computeDiff(comparingVersion.content, selectedArticle?.content || '');
                                const hasChanges = diffs.some(d => d.type !== 'unchanged');
                                
                                if (!hasChanges) {
                                  return (
                                    <div className={styles.noChangesMsg}>
                                      <ShieldCheck size={20} />
                                      <span>Current version is identical to v{comparingVersion.version_number}. No structural changes detected.</span>
                                    </div>
                                  );
                                }

                                return diffs.map((line, idx) => (
                                  <div key={idx} className={`${styles.diffLine} ${styles[line.type]}`}>
                                    <span className={styles.diffMarker}>
                                      {line.type === 'added' ? '+' : line.type === 'removed' ? '-' : ' '}
                                    </span>
                                    <pre>{line.value || ' '}</pre>
                                  </div>
                                ));
                              })()}
                            </div>
                          </div>

                        ) : (
                          <NexusMarkdown content={selectedArticle?.content || editContent} />
                        )}
                      </div>

                    </div>
                  </>
                )}
              </div>
            )}
            </div>
          </motion.div>
        </>
      )}
    </AnimatePresence>
    </div>
  );
};