Spaces:
Paused

File size: 46,318 Bytes
970c341
9483939
4a6adfb
 
 
 
 
 
72fac6f
2bb9807
055d291
 
4777084
055d291
4777084
d8eb3eb
5eb4857
4a6adfb
 
 
56410fa
9483939
 
6e84d1b
0dac228
933ab8f
a7ed06e
 
9483939
 
5eb4857
4e329ec
5eb4857
4e329ec
16bf212
5eb4857
 
72fac6f
 
055d291
4e329ec
055d291
4e329ec
5eb4857
 
d8eb3eb
4a6adfb
5eb4857
 
 
 
 
4a6adfb
5eb4857
 
 
 
 
e1899ac
 
 
5eb4857
e1899ac
fb7ec09
a216d04
9357dea
4ae2101
fb7ec09
bd0fa52
02e4bcb
 
0ea20e3
 
213ab14
9285285
bd0fa52
10ae211
 
 
 
 
 
 
 
 
4c985e0
4ae2101
5eb4857
56410fa
16bf212
9357dea
 
d8eb3eb
16bf212
 
9357dea
 
 
c65ce91
 
 
9357dea
c65ce91
9357dea
 
4e329ec
9357dea
 
 
d8eb3eb
9357dea
 
4e329ec
9357dea
4e329ec
 
 
9357dea
 
 
7f5dd8e
9357dea
 
 
 
 
7f5dd8e
 
 
 
16bf212
7f5dd8e
 
9357dea
 
 
 
 
 
 
 
 
 
7f5dd8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ea20e3
 
 
 
 
 
9357dea
 
 
16bf212
4e329ec
16bf212
5eb4857
 
f51757d
 
a8ee82f
 
16bf212
5eb4857
d8eb3eb
fb7ec09
d8eb3eb
 
 
6e84d1b
 
 
 
4a6adfb
da4d992
4a6adfb
 
 
 
 
 
 
6e84d1b
 
 
 
 
16bf212
4e329ec
4a6adfb
4e329ec
 
 
 
 
 
 
 
 
10ae211
4a6adfb
fb7ec09
5eb4857
9483939
 
 
 
 
4ae2101
5eb4857
213ab14
 
 
 
 
 
4e329ec
213ab14
 
 
 
 
 
 
d8eb3eb
213ab14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ae2101
 
 
 
 
10ae211
4ae2101
 
10ae211
4ae2101
 
10ae211
4a6adfb
4ae2101
 
10ae211
4ae2101
 
5eb4857
a8ee82f
 
 
4777084
a8ee82f
 
d8eb3eb
a8ee82f
 
 
 
da4d992
 
a8ee82f
 
 
5eb4857
 
d8eb3eb
a8ee82f
4e329ec
a8ee82f
d8eb3eb
5eb4857
 
 
 
 
72fac6f
5eb4857
 
0d8550d
5eb4857
 
4e329ec
 
5eb4857
 
 
 
 
fb7ec09
 
 
2131f07
4e329ec
fb7ec09
 
 
 
e1899ac
 
4d5026d
 
e1899ac
 
 
 
 
 
4d5026d
213ab14
4d5026d
 
 
5eb4857
a216d04
5eb4857
0d8550d
5eb4857
 
0d8550d
5eb4857
4e329ec
 
a216d04
 
5eb4857
 
 
 
 
 
 
0d8550d
5eb4857
 
 
933ab8f
4e329ec
 
5eb4857
 
 
 
 
4e329ec
5eb4857
428a35c
5eb4857
4a6adfb
 
 
 
5eb4857
428a35c
4a6adfb
 
 
 
428a35c
 
 
 
8ad9c72
055d291
8ad9c72
 
055d291
428a35c
 
 
 
8ad9c72
4a6adfb
 
 
428a35c
213ab14
 
428a35c
 
0720a96
4a6adfb
 
 
 
 
 
 
 
4e329ec
4a6adfb
 
428a35c
4a6adfb
5eb4857
 
 
 
33ef5cd
5eb4857
9483939
5eb4857
 
055d291
 
 
 
 
 
 
 
4ae2101
0dac228
055d291
 
 
0dac228
 
055d291
0dac228
055d291
 
 
 
 
 
 
0dac228
16bf212
e8ff64c
16bf212
 
 
 
 
 
 
 
 
 
055d291
0dac228
 
 
055d291
a7ed06e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
055d291
a7ed06e
 
 
055d291
4a6adfb
 
 
 
 
 
 
 
 
 
 
 
4e329ec
 
5eb4857
d8eb3eb
4e329ec
4a6adfb
d8eb3eb
 
 
 
87d18ae
d8eb3eb
 
7e1cd85
 
 
72fac6f
4e329ec
d8eb3eb
4e329ec
d8eb3eb
16bf212
 
 
 
 
 
 
 
 
9357dea
 
 
 
 
16bf212
9357dea
 
d8eb3eb
 
 
 
4e329ec
d8eb3eb
3c4c08a
 
 
 
d8eb3eb
 
 
 
 
 
 
 
 
 
4e329ec
87d18ae
d8eb3eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
d8eb3eb
 
5eb4857
72fac6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e79b7f5
72fac6f
 
 
 
 
 
 
16bf212
d3e606c
 
d8eb3eb
16bf212
 
 
 
 
 
 
 
 
 
213ab14
56410fa
d8eb3eb
 
 
 
 
 
 
 
 
16bf212
 
 
d8eb3eb
 
56410fa
d3e606c
ebf9e6f
16bf212
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8eb3eb
b9b4ddb
16bf212
 
 
 
 
 
 
 
5eb4857
 
16bf212
d8eb3eb
 
2bb9807
16bf212
2bb9807
 
 
16bf212
d8eb3eb
 
16bf212
 
 
 
 
 
 
 
5eb4857
d8eb3eb
 
16bf212
 
bd0fa52
 
16bf212
b9b4ddb
 
 
 
 
 
 
 
 
 
 
 
16bf212
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
933ab8f
16bf212
5eb4857
4a6adfb
16bf212
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1899ac
 
 
16bf212
 
 
 
 
 
 
 
5eb4857
 
 
d8eb3eb
4a6adfb
16bf212
213ab14
d8eb3eb
213ab14
 
 
5eb4857
e1899ac
4ae2101
 
 
e1899ac
4a6adfb
 
 
4ae2101
 
 
 
e1899ac
 
4a6adfb
d8eb3eb
 
e1899ac
4ae2101
d8eb3eb
 
e1899ac
4ae2101
 
 
 
d8eb3eb
4a6adfb
d8eb3eb
 
 
 
4ae2101
d8eb3eb
 
 
4ae2101
da4d992
 
4a6adfb
 
da4d992
b9ee4f4
da4d992
 
 
e1899ac
 
 
d8eb3eb
 
 
e1899ac
10ae211
4ae2101
10ae211
4a6adfb
10ae211
 
 
 
 
 
4a6adfb
 
 
 
4ae2101
 
 
 
10ae211
 
4ae2101
 
4a6adfb
4ae2101
 
 
4a6adfb
 
 
7e1cd85
 
 
 
 
4ae2101
 
 
 
d8eb3eb
 
 
9285285
f7f94e7
 
d8eb3eb
 
4a6adfb
d8eb3eb
4ae2101
d8eb3eb
4ae2101
 
 
 
a7ed06e
4ae2101
 
 
a7ed06e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8eb3eb
 
4ae2101
 
 
56410fa
d8eb3eb
7e1cd85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
4e329ec
5eb4857
e1899ac
5eb4857
213ab14
e1899ac
933ab8f
 
 
 
4a6adfb
 
 
 
 
 
 
 
 
 
 
 
933ab8f
4a6adfb
 
 
933ab8f
 
4a6adfb
933ab8f
e1899ac
933ab8f
 
 
 
e1899ac
 
 
 
 
4e329ec
933ab8f
ab51920
 
 
 
 
 
 
933ab8f
 
4e329ec
 
 
 
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
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { StatusBadge } from './Badges';
import {
  api,
  NexusMarkdown,
  getFileIcon,
  getStorageKey,
  useMentions,
  MentionOverlay,
  RichEditor,
  useTheme,
  useNotification
} from '@nexus/shared';

import type { Ticket, Message } from '@nexus/shared';
import styles from './ThreadView.module.css';

import {
  ArrowLeft,
  Send,
  Paperclip,
  Sparkles,
  Maximize2,
  RefreshCcw,
  Loader2,
  Trash2,
  BookOpen,
  Download
} from 'lucide-react';

interface ThreadViewProps {
  ticket: Ticket;
  onBack: () => void;
  onNavigate?: (ticket: { id: string }) => void;
  onNavigateArticle?: (articleId: string) => void;
}

export const ThreadView: React.FC<ThreadViewProps> = ({ ticket: initialTicket, onBack, onNavigate, onNavigateArticle }) => {
  const { theme } = useTheme();
  const { alert, confirm } = useNotification();
  const [ticket, setTicket] = useState<Ticket>(initialTicket);

  const [messages, setMessages] = useState<Message[]>([]);
  const [newMessage, setNewMessage] = useState("");
  const [sending, setSending] = useState(false);
  const [currentUser, setCurrentUser] = useState<{ id: string, full_name: string } | null>(null);

  // Description Edit State
  const [isEditingDesc, setIsEditingDesc] = useState(false);
  const [descDraft, setDescDraft] = useState(initialTicket.description);
  const [savingDesc, setSavingDesc] = useState(false);
  const [isUploading, setIsUploading] = useState(false);

  // Feedback States
  const [ratingDraft, setRatingDraft] = useState<number | null>(ticket.rating || null);
  const [hoverRating, setHoverRating] = useState<number | null>(null);
  const [commentDraft, setCommentDraft] = useState("");
  const [isSubmittingFeedback, setIsSubmittingFeedback] = useState(false);
  const [showReopenModal, setShowReopenModal] = useState(false);
  const [reopenReason, setReopenReason] = useState("");
  const [isReopening, setIsReopening] = useState(false);

  // AI Intensity States
  const [isRegeneratingSummary, setIsRegeneratingSummary] = useState(false);
  const [isEscalating, setIsEscalating] = useState(false);
  const [historyEvents, setHistoryEvents] = useState<any[]>([]);
  const [showConfirmEscalate, setShowConfirmEscalate] = useState(false);

  // Sidebar States
  const [isSidebarOpen, setIsSidebarOpen] = useState(false);
  const [isLeftSidebarOpen, setIsLeftSidebarOpen] = useState(false);
  const [forbidden, setForbidden] = useState(false);
  const [sidebarWidth, setSidebarWidth] = useState(400);
  const [isResizing, setIsResizing] = useState(false);
  const [sidebarTab, setSidebarTab] = useState<'messages' | 'files' | 'history'>('messages');

  const {
    filteredUsers,
    showMentionList,
    selectedMentionIndex,
    setSelectedMentionIndex,
    cursorPos,
    handleInputChange,
    getMentionText,
    closeMentions
  } = useMentions({ workspaceId: ticket?.workspace_id });

  const bottomRef = useRef<HTMLDivElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const isRefreshing = useRef(false);
  const [isLoading, setIsLoading] = useState(false);

  const refreshData = useCallback(async (bypassCache = false) => {
    if (isRefreshing.current) return;
    isRefreshing.current = true;
    setIsLoading(true);
    
    const watchdog = setTimeout(() => {
      // Release the refresh lock so users can retry after a hung request.
      // Without this, isRefreshing stays true indefinitely if the request never
      // resolves, silently blocking every subsequent manual refresh.
      setIsLoading(false);
      isRefreshing.current = false;
    }, 30000);

    try {
      const ticketId = initialTicket.id;
      const ticketUrl = `tickets/${ticketId}/${bypassCache ? '?bypass_cache=true' : ''}`;
      const [ticketResp, messagesResp, auditResp] = await Promise.all([
        api.get(ticketUrl),
        api.get(`tickets/${ticketId}/messages/`),
        api.get(`tickets/${ticketId}/audit/`)
      ]);

      setTicket(ticketResp.data);
      setDescDraft(ticketResp.data.description);
      setMessages(messagesResp.data);
      
      // Transform raw audit logs into UI-friendly history events
      const rawLogs = auditResp.data;
      const auditEvents = rawLogs.map((log: any) => {
        let label = log.action.toUpperCase();
        let icon = '📝';
        let detail = `Action performed by ${log.actor_name}`;

        if (log.action === 'create') { icon = '🎫'; label = 'INCIDENT LOGGED'; detail = 'Incident initialized via portal.'; }
        else if (log.action === 'escalation') { icon = '🚨'; label = 'CRITICAL ESCALATION'; detail = 'Priority elevated to P0 for lead intervention.'; }
        else if (log.action === 'update' && log.new_value?.status === 'RESOLVED') { icon = '✅'; label = 'RESOLVED'; detail = 'Agent has finalized the resolution.'; }
        else if (log.action === 'update' && log.new_value?.status === 'ACKNOWLEDGED') { icon = '🛡️'; label = 'ACKNOWLEDGED'; detail = 'Technical specialist has claimed this ticket.'; }
        else if (log.action === 'update' && log.new_value?.status === 'IN_PROGRESS') { icon = '⚙️'; label = 'IN PROGRESS'; detail = 'Active investigation is underway.'; }
        else if (log.action === 'update' && log.new_value?.priority) { icon = '⚡'; label = 'PRIORITY CHANGE'; detail = `Priority adjusted to ${log.new_value.priority}.`; }
        else if (log.action === 'update' && log.new_value?.assigned_to) { icon = '👥'; label = 'ASSIGNMENT'; detail = `Assigned to ${log.new_value.assigned_to_name || 'Technical Specialist'}.`; }
        else if (log.action === 'update' && log.new_value?.title) { icon = '✏️'; label = 'TITLE UPDATED'; detail = 'Subject was refined for clarity.'; }
        else if (log.action === 'reopen') { icon = '🔄'; label = 'REOPENED'; detail = log.new_value?.reason || 'Resumed for further review.'; }

        return {
          id: log.id,
          time: log.created_at,
          label,
          detail,
          icon
        };
      });

      const messageEvents = (messagesResp.data || []).map((m: any) => {
        const isCustomer = m.sender_role?.toLowerCase().includes('customer');
        return {
          id: m.id,
          time: m.created_at,
          label: isCustomer ? 'CLIENT MESSAGE' : 'AGENT RESPONSE',
          detail: m.content.length > 100 ? m.content.substring(0, 100) + '...' : m.content,
          icon: isCustomer ? '💬' : '🎧'
        };
      });

      const combinedEvents = [...auditEvents, ...messageEvents].sort((a, b) => 
        new Date(b.time).getTime() - new Date(a.time).getTime()
      );

      setHistoryEvents(combinedEvents);
      setForbidden(false);
    } catch (err: any) {
      console.error("Failed to refresh data", err);
      if (err.response?.status === 403) {
        setForbidden(true);
      }
    } finally {
      clearTimeout(watchdog);
      setIsLoading(false);
      isRefreshing.current = false;
    }
  }, [initialTicket.id]);

  useEffect(() => {
    // Standard data fetch on mount, NO force-refresh (bypassCache=false)
    refreshData(false);
    const userString = localStorage.getItem(getStorageKey('user'));
    if (userString) setCurrentUser(JSON.parse(userString));
  }, [initialTicket.id]); // ONLY trigger on ID change, ignore refreshData ref to avoid loops

  // Real-time Event Listener
  useEffect(() => {
    const handleLiveEvent = (event: Event) => {
      const customEvent = event as CustomEvent;
      const data = customEvent.detail;
      if (data.event === 'summary_updated' && data.ticket_id === ticket.id) {
        refreshData();
        setIsRegeneratingSummary(false);
      } else if ((data.event === 'ticket_updated' || data.event === 'new_message') && data.ticket_id === ticket.id) {
        if (data.event === 'new_message') {
          setMessages(prev => {
            if (prev.some(m => m.id === data.message.id)) return prev;
            return [...prev, data.message];
          });
          setTimeout(() => bottomRef.current?.scrollIntoView({ behavior: 'smooth' }), 50);
        } else {
          refreshData();
        }
      }
    };

    window.addEventListener('nexus-live-event', handleLiveEvent);
    return () => window.removeEventListener('nexus-live-event', handleLiveEvent);
  }, [ticket?.id]); // Removed refreshData from dependencies to prevent listener churn loops

  // Reset state only when navigating to a DIFFERENT ticket ID
  useEffect(() => {
    setTicket(initialTicket);
    setMessages([]);
    setDescDraft(initialTicket.description);
    setNewMessage("");
    setRatingDraft(initialTicket.rating || null);
    setIsEditingDesc(false);
    setShowConfirmEscalate(false);
    setIsRegeneratingSummary(false);
    closeMentions();
  }, [initialTicket.id]); // ONLY trigger on ID change

  useEffect(() => {
    if (isSidebarOpen) {
      setTimeout(() => {
        bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
      }, 100);
    }
  }, [messages, isSidebarOpen, sidebarTab]);

  // Sidebar Resize Logic
  const handleMouseDown = useCallback((e: React.MouseEvent) => {
    e.preventDefault();
    setIsResizing(true);
  }, []);

  useEffect(() => {
    const handleMouseMove = (e: MouseEvent) => {
      if (!isResizing) return;
      const newWidth = window.innerWidth - e.clientX - 32;
      if (newWidth > 320 && newWidth < window.innerWidth * 0.5) {
        setSidebarWidth(newWidth);
      }
    };
    const handleMouseUp = () => setIsResizing(false);

    if (isResizing) {
      document.addEventListener('mousemove', handleMouseMove);
      document.addEventListener('mouseup', handleMouseUp);
      document.body.style.cursor = 'col-resize';
    } else {
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
      document.body.style.cursor = 'default';
    }

    return () => {
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
    };
  }, [isResizing]);

  // --- MENTION LOGIC ---
  const handleMentionInput = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    const val = e.target.value;
    const position = e.target.selectionStart;
    setNewMessage(val);
    handleInputChange(val, position);
  };

  const handleInsertMention = (user: any) => {
    const textBeforeMention = newMessage.slice(0, cursorPos).replace(/@(\w*)$/, "");
    const textAfterMention = newMessage.slice(cursorPos);
    const mentionText = getMentionText(user);

    const newValue = textBeforeMention + mentionText + textAfterMention;
    setNewMessage(newValue);
    closeMentions();
  };

  const handleSend = async () => {
    if (!newMessage.trim() || sending) return;
    const content = newMessage;
    const tempId = `temp-${Date.now()}`;
    const optimisticMsg: any = {
      id: tempId,
      content: content,
      sender_id: currentUser?.id || 'unknown',
      sender_name: currentUser?.full_name || "You",
      sender_role: "customer",
      is_internal: false,
      created_at: new Date().toISOString(),
      attachments: [],
      is_sending: true
    };
    setMessages(prev => [...prev, optimisticMsg]);
    setNewMessage("");
    setSending(true);
    try {
      const resp = await api.post(`tickets/${ticket.id}/messages/`, { content, is_internal: false });
      setMessages(prev => prev.map(m => m.id === tempId ? resp.data : m));
    } catch {
      setMessages(prev => prev.filter(m => m.id !== tempId));
      setNewMessage(content);
    } finally {
      setSending(false);
    }
  };

  const handleSaveDescription = async () => {
    setSavingDesc(true);
    try {
      const resp = await api.patch(`tickets/${ticket.id}/`, { description: descDraft });
      setTicket(resp.data);
      setIsEditingDesc(false);
    } catch {
      console.error("Failed to update description");
    } finally {
      setSavingDesc(false);
    }
  };

  const handleRegenerateSummary = async () => {
    setIsRegeneratingSummary(true);
    try {
      await api.post(`tickets/${ticket.id}/summarize/`);
    } catch {
      setIsRegeneratingSummary(false);
    }
  };

  const handleReopen = async () => {
    if (!reopenReason.trim()) return;
    setIsReopening(true);
    try {
      await api.post(`tickets/${ticket.id}/reopen/`, { reason: reopenReason });
      setReopenReason("");
      setShowReopenModal(false);
      refreshData();
    } catch (err) {
      console.error("Reopen failed", err);
    } finally {
      setIsReopening(false);
    }
  };

  const handleEscalate = async () => {
    setIsEscalating(true);
    try {
      const resp = await api.post(`tickets/${ticket.id}/escalate/`);
      setTicket(resp.data);
      setShowConfirmEscalate(false);
      const messagesResp = await api.get(`tickets/${ticket.id}/messages/`);
      setMessages(messagesResp.data);
    } catch {
      console.error("Escalation failed");
    } finally {
      setIsEscalating(false);
    }
  };

  const handleSubmitFeedback = async () => {
    if (!ratingDraft) return;
    setIsSubmittingFeedback(true);
    try {
      const resp = await api.post(`tickets/${ticket.id}/feedback/`, {
        rating: ratingDraft,
        comment: commentDraft
      });
      setTicket({ ...ticket, rating: resp.data.rating, feedback_comment: resp.data.comment });
    } catch {
      console.error("Feedback submission failed");
    } finally {
      setIsSubmittingFeedback(false);
    }
  };

  const handlePaste = async (e: React.ClipboardEvent<HTMLTextAreaElement>, isMainDesc: boolean) => {
    const items = e.clipboardData.items;
    let fileItem = null;
    for (let i = 0; i < items.length; i++) {
      if (items[i].kind === "file") {
        fileItem = items[i];
        break;
      }
    }
    if (fileItem) {
      e.preventDefault();
      const file = fileItem.getAsFile();
      if (!file) return;
      await handleUpload(file, isMainDesc);
    }
  };

  const handleUpload = async (file: File, isMainDesc: boolean) => {
    if (file.size > 10 * 1024 * 1024) {
      alert("File is too large (max 10MB).", { type: 'error', title: 'Upload Restriction' });
      return;
    }

    setIsUploading(true);
    const formData = new FormData();
    formData.append("file", file);
    const isImage = file.type.startsWith("image/");
    const uploadId = Date.now() % 10000;
    const placeholder = isImage
      ? `\n![Uploading ${file.name} (#${uploadId})...]()\n`
      : `\n[Uploading ${file.name} (#${uploadId})...]()\n`;

    if (isMainDesc) setDescDraft((curr: string) => curr + placeholder);
    else setNewMessage((curr: string) => curr + placeholder);

    try {
      const resp = await api.post(`tickets/${ticket.id}/attachments/`, formData);
      const baseUrl = api.defaults.baseURL || "";
      const backendBase = baseUrl.endsWith('/') ? baseUrl : baseUrl + '/';
      const downloadUrl = `${backendBase}tickets/attachments/${resp.data.id}/download/`;
      const finalMarkdown = isImage ? `\n![Screenshot](${downloadUrl})\n` : `\n${getFileIcon(file.name)} [${file.name}](${downloadUrl})\n`;

      if (isMainDesc) setDescDraft((curr: string) => curr.replace(placeholder, finalMarkdown));
      else setNewMessage((curr: string) => curr.replace(placeholder, finalMarkdown));
      setTicket(curr => ({ ...curr, attachments: [...(curr.attachments || []), resp.data] }));
    } catch {
      if (isMainDesc) setDescDraft((curr: string) => curr.replace(placeholder, ""));
      else setNewMessage((curr: string) => curr.replace(placeholder, ""));
    } finally {
      setIsUploading(false);
    }
  };

  const formatETA = (dateStr: string) => {
    if (!dateStr) return "PENDING";
    const date = new Date(dateStr);
    return date.toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }).toUpperCase();
  };

  const handleDeleteMessage = async (messageId: string) => {
    const confirmed = await confirm("Purge this message from your history?", {
      title: "Purge Message",
      confirmLabel: "Purge",
      type: "error",
      danger: true
    });
    if (!confirmed) return;
    api.delete(`tickets/${ticket.id}/messages/${messageId}/`).then(() => {
      setMessages(prev => prev.filter(m => m.id !== messageId));
    }).catch(() => {
      alert("Deletion failed.", { type: 'error', title: 'System Error' });
    });
  };


  const handleDeleteAttachment = async (attachmentId: string) => {
    const confirmed = await confirm("Permanently remove this asset?", {
      title: "Remove Asset",
      confirmLabel: "Remove",
      type: "error",
      danger: true
    });
    if (!confirmed) return;
    try {
      // Correct endpoint path matches main.py prefix + attachments.py route
      await api.delete(`tickets/attachments/${attachmentId}/`);
      setTicket(curr => ({ 
        ...curr, 
        attachments: (curr.attachments || []).filter(a => a.id !== attachmentId) 
      }));
      setMessages(prev => prev.map(m => ({ 
        ...m, 
        attachments: (m.attachments || []).filter(a => a.id !== attachmentId) 
      })));
    } catch (err) {
      console.error("Asset deletion failed", err);
      alert("Failed to delete attachment. Please verify permissions.", { type: 'error', title: 'Access Denied' });
    }
  };


  const handleFileDownload = async (attId: string, fileName: string) => {
    try {
      const response = await api.get(`tickets/attachments/${attId}/download/`, {
        responseType: 'blob'
      });
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', fileName || 'attachment');
      document.body.appendChild(link);
      link.click();
      link.remove();
      window.URL.revokeObjectURL(url);
    } catch (error) {
      console.error("Download failed:", error);
      alert("Authenticated asset download failed. Session may have expired.", { type: 'error', title: 'Download Error' });
    }
  };


  if (forbidden) {
    return (
      <div className={styles.container} style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', textAlign: 'center', padding: 40 }}>
        <div className="mesh-bg" />
        <div style={{ fontSize: 64, marginBottom: 24 }}>🛡️</div>
        <h1 style={{ fontWeight: 900, letterSpacing: '-0.02em', marginBottom: 12 }}>ACCESS RESTRICTED</h1>
        <p style={{ opacity: 0.6, maxWidth: 400, margin: '0 auto 32px', lineHeight: 1.6 }}>Your current neural credentials do not permit access to this specific operational thread.</p>
        <button onClick={onBack} className={styles.btnPrimary} style={{ padding: '12px 32px' }}>RETURN TO DASHBOARD</button>
      </div>
    );
  }

  if (!ticket) return null;

  return (
    <div className={styles.container}>
      <div className="mesh-bg" />

      <header className={styles.header}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 20 }}>
          <button className={styles.headerBtn} onClick={onBack} title="Go Back">
            <ArrowLeft size={20} />
          </button>
          <div className={styles.headerTitleArea}>
            <div className={styles.ticketIdBadge}>#{ticket.id.slice(0, 8).toUpperCase()}</div>
            {ticket.is_escalated && (
              <div className={styles.escalatedBadge}>ESCALATED</div>
            )}
            <h1 className={styles.mainTitle} style={{ color: theme === 'light' ? '#000000' : 'var(--primary)' }}>{ticket.title}</h1>
          </div>
        </div>

        <div className={styles.headerActions}>
          <div style={{ display: 'flex', gap: 6, marginRight: 12 }}>
            <button className={styles.toggleBtn} onClick={() => setIsLeftSidebarOpen(!isLeftSidebarOpen)} title="Toggle Analysis">
              <Maximize2 size={16} style={{ transform: 'rotate(90deg)' }} color={isLeftSidebarOpen ? 'var(--primary)' : 'var(--text-muted)'} />
            </button>
            <button className={styles.toggleBtn} onClick={() => setIsSidebarOpen(!isSidebarOpen)} title="Toggle Feed">
              <Maximize2 size={16} color={isSidebarOpen ? 'var(--primary)' : 'var(--text-muted)'} />
            </button>
          </div>

          <button 
            className={styles.headerBtn} 
            onClick={() => refreshData(true)} 
            disabled={isLoading}
            title="Refresh Intelligence"
            style={{ opacity: isLoading ? 0.5 : 1, cursor: isLoading ? 'not-allowed' : 'pointer', marginRight: 12 }}
          >
            <RefreshCcw size={18} className={isLoading ? styles.spin : ''} />
          </button>
          {['RESOLVED', 'CLOSED'].includes((ticket.status || '').toUpperCase()) && (
            <button onClick={() => setShowReopenModal(true)} disabled={isReopening} className={`${styles.btn} ${styles.btnSecondary}`} style={{ padding: '8px 16px' }}>
              {isReopening ? 'REOPENING...' : 'REOPEN TICKET'}
            </button>
          )}
          {!['RESOLVED', 'CLOSED'].includes((ticket.status || '').toUpperCase()) && !ticket.is_escalated && (
            <button onClick={() => setShowConfirmEscalate(true)} disabled={isEscalating} className={`${styles.btn} ${styles.btnEscalate}`} style={{ padding: '8px 16px' }}>
              {isEscalating ? 'ESCALATING...' : 'ESCALATE'}
            </button>
          )}
        </div>
      </header>

      <div className={styles.propertyStrip}>
        <div className={styles.propertySlot}>
          <div className={styles.slotLabel}>TICKET PRIORITY</div>
          <div className={styles.slotValueArea}>
            <div className={styles.priorityDot} style={{ background: ticket.priority === 'P0' ? 'var(--error)' : 'var(--primary)' }} />
            <span className={styles.slotValue}>{ticket.priority?.toUpperCase() || "STANDARD"}</span>
          </div>
        </div>
        <div className={styles.propertySlot}>
          <div className={styles.slotLabel}>ASSIGNED AGENT</div>
          <div className={styles.slotValueArea}>
            <div className={styles.assigneeAvatar}>{ticket.assigned_name ? ticket.assigned_name[0] : "N"}</div>
            <span className={styles.slotValue}>{ticket.assigned_name || "Nexus AI Agent"}</span>
          </div>
        </div>
        <div className={styles.propertySlot}>
          <div className={styles.slotLabel}>OPERATIONAL STATUS</div>
          <div className={styles.slotValueArea}>
            <StatusBadge status={ticket.status} />
          </div>
        </div>
        <div className={styles.propertySlot}>
          <div className={styles.slotLabel}>ESTIMATED RESOLUTION</div>
          <div className={styles.slotValueArea}>
            <span className={styles.slotValue}>{formatETA(ticket.expected_resolution_at || "")}</span>
          </div>
        </div>
      </div>

      <div className={styles.horizontalWorkspace}>
        {/* Left Sidebar: Analysis & Context */}
        <aside className={`${styles.leftSidebar} ${!isLeftSidebarOpen ? styles.leftSidebarCollapsed : ''}`}>
          {/* Relevant Knowledge Section */}
          <div className={styles.sidebarSection}>
            <div className={styles.sidebarSectionTitle}>Relevant Knowledge</div>
            {ticket.similar_articles && ticket.similar_articles.length > 0 ? (
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                {ticket.similar_articles?.map((art) => (
                  <div 
                    key={art.id} 
                    className={styles.knowledgeItem}
                    onClick={() => onNavigateArticle?.(art.id)}
                  >
                    <BookOpen size={16} color="var(--primary)" />
                    <span className={styles.knowledgeTitle}>{art.title}</span>
                  </div>
                ))}
              </div>
            ) : (
              <div style={{ fontSize: 11, color: 'var(--text-muted)', textAlign: 'center', padding: '20px 0' }}>No relevant articles found.</div>
            )}
          </div>

          {/* Similar Tickets Section */}
          <div className={styles.sidebarSection}>
            <div className={styles.sidebarSectionTitle}>Historical Parallels</div>
            {ticket.similar_tickets && ticket.similar_tickets.length > 0 ? (
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                {ticket.similar_tickets?.map((sim) => (
                  <div 
                    key={sim.id} 
                    className={styles.parallelItem}
                    onClick={() => onNavigate?.({ id: sim.id })}
                  >
                    <div className={styles.parallelHeader}>
                      <span className={styles.matchBadge}>{(sim.similarity * 100).toFixed(0)}% MATCH</span>
                      <StatusBadge status={sim.status} />
                    </div>
                    <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--text-main)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{sim.title}</div>
                  </div>
                ))}
              </div>
            ) : (
              <div style={{ fontSize: 11, color: 'var(--text-muted)', textAlign: 'center', padding: '20px 0' }}>No historical overlaps detected.</div>
            )}
          </div>
        </aside>

        <main className={styles.mainContent}>
          {/* AI Intelligence Summary */}
          {ticket.status?.toUpperCase() !== 'OPEN' && (
            <div className={styles.aiIntelligenceCard}>
            <div className={styles.aiHeader}>
              <div className={styles.aiBadge}>
                <Sparkles size={16} /> AI Intelligence Summary
              </div>
              <button 
                className={styles.btnSecondary} 
                style={{ padding: '6px 12px', fontSize: 10, height: 'auto' }}
                onClick={handleRegenerateSummary}
                disabled={isRegeneratingSummary}
              >
                <RefreshCcw size={12} className={isRegeneratingSummary ? styles.spin : ''} /> {isRegeneratingSummary ? 'Regenerating...' : 'Regenerate'}
              </button>
            </div>
            <div className={styles.intelligenceSurface}>
              {isRegeneratingSummary ? (
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, color: 'var(--primary)', fontWeight: 700 }}>
                  <Loader2 size={18} className={styles.spin} />
                  <span>Synthesizing neural insights...</span>
                </div>
              ) : ticket.summary ? (
                <NexusMarkdown content={ticket.summary} />
              ) : (
                <div style={{ opacity: 0.5, fontStyle: "italic" }}>
                  Neural core is synthesizing high-fidelity resolution steps...
                </div>
              )}
            </div>
          </div>
          )}

          {/* Duplicate Alert HUD */}
          {ticket.status === 'CLOSED' && ticket.duplicate_of_id && (
            <div className={styles.duplicateAlert}>
              <div className={styles.duplicateIcon}><Maximize2 size={20} /></div>
              <div className={styles.duplicateContent}>
                <div className={styles.duplicateTitle}>Duplicate Signal Detected</div>
                <div className={styles.duplicateSub}>
                  This incident has been linked to <span className={styles.duplicateLink} onClick={() => onNavigate?.({ id: ticket.duplicate_of_id! })}>#{ticket.duplicate_of_id.slice(0, 8).toUpperCase()}</span>.
                </div>
              </div>
            </div>
          )}

          {/* Ticket Description Card */}
          <section className={styles.descriptionCard}>
            <div className={styles.sectionHeader}>
              <div className={styles.sectionLabel}>Ticket details</div>
              {!['RESOLVED', 'CLOSED'].includes((ticket.status || '').toUpperCase()) && !isEditingDesc && (
                <button 
                  className={styles.btnSecondary} 
                  style={{ padding: '6px 12px', fontSize: 10 }}
                  onClick={() => setIsEditingDesc(true)}
                >
                  Edit Description
                </button>
              )}
            </div>

            {isEditingDesc ? (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                <RichEditor 
                  value={descDraft}
                  onChange={setDescDraft}
                  ticketId={ticket.id}
                  placeholder="Provide context, logs, or steps to reproduce..."
                />
                <div style={{ display: 'flex', gap: 12, justifyContent: 'flex-end' }}>
                  <button onClick={() => setIsEditingDesc(false)} className={styles.btnSecondary} style={{ padding: '8px 20px' }}>CANCEL</button>
                  <button 
                    className={styles.btnPrimary} 
                    onClick={handleSaveDescription}
                    disabled={savingDesc}
                    style={{ padding: '8px 24px' }}
                  >
                    {savingDesc ? <Loader2 size={16} className={styles.spin} /> : 'Save Description'}
                  </button>
                </div>
              </div>
            ) : (
              <div className={styles.descriptionContent}>
                <NexusMarkdown content={ticket.description || "No description provided."} />
              </div>
            )}
          </section>
          
          {/* Resolution Overview (Visible when resolved/closed) */}
          {(ticket.status === 'RESOLVED' || ticket.status === 'CLOSED' || ticket.resolution_text) && (
            <section className={styles.descriptionCard} style={{ background: 'rgba(16, 185, 129, 0.05)', borderColor: 'var(--success)', marginTop: 24 }}>
              <div className={styles.sectionHeader}>
                <div className={styles.sectionLabel} style={{ color: 'var(--success)' }}>Resolution</div>
              </div>
              <div className={styles.descriptionContent}>
                <NexusMarkdown content={ticket.resolution_text || "_Final documentation of the resolution is being synchronized to the portal..._"} />
              </div>
            </section>
          )}

          {/* Feedback Section (Conditional) */}
          {ticket.status === 'RESOLVED' && !ticket.rating && (
            <div className={styles.feedbackSurface}>
              <div style={{ fontSize: 24, fontWeight: 900, marginBottom: 12 }}>How was the resolution?</div>
              <p style={{ color: 'var(--text-muted)', marginBottom: 32 }}>Your feedback helps us optimize the Nexus neural core.</p>
              
              <div style={{ display: 'flex', justifyContent: 'center', gap: 16, marginBottom: 40 }}>
                {[1, 2, 3, 4, 5].map(star => (
                  <div 
                    key={star}
                    onMouseEnter={() => setHoverRating(star)}
                    onMouseLeave={() => setHoverRating(null)}
                    onClick={() => setRatingDraft(star)}
                    style={{ cursor: 'pointer', fontSize: 32, transition: 'all 0.2s', transform: (hoverRating || ratingDraft || 0) >= star ? 'scale(1.2)' : 'scale(1)' }}
                  >
                    {(hoverRating || ratingDraft || 0) >= star ? '⭐' : '☆'}
                  </div>
                ))}
              </div>

              <textarea 
                className={styles.feedbackTextarea}
                placeholder="Additional testimony (optional)..."
                value={commentDraft}
                onChange={(e) => setCommentDraft(e.target.value)}
              />

              <button 
                className={styles.btnPrimary} 
                style={{ width: '100%', padding: '16px' }}
                onClick={handleSubmitFeedback}
                disabled={isSubmittingFeedback || !ratingDraft}
              >
                {isSubmittingFeedback ? 'Syncing...' : 'Submit Satisfaction Signal'}
              </button>
            </div>
          )}

          {ticket.rating && (
            <div className={styles.feedbackSurface} style={{ textAlign: 'left', background: 'rgba(16, 185, 129, 0.05)', borderColor: 'var(--success)' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
                <div style={{ fontSize: 10, fontWeight: 900, color: 'var(--success)', textTransform: 'uppercase' }}>User Testimony Logged</div>
                <div style={{ fontSize: 20 }}>{'⭐'.repeat(ticket.rating)}</div>
              </div>
              <div style={{ fontSize: 15, fontWeight: 500, color: 'var(--text-main)', fontStyle: 'italic' }}>
                "{ticket.feedback_comment || "No written testimony provided."}"
              </div>
            </div>
          )}
        </main>

        {/* Right Sidebar: Feed */}
        {isSidebarOpen && (
          <div onMouseDown={handleMouseDown} style={{ width: 12, cursor: 'col-resize', zIndex: 10, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: "0 -6px", opacity: isResizing ? 1 : 0 }} className="sidebar-resizer">
            <div style={{ width: 2, height: 60, background: 'var(--primary)', borderRadius: 2, opacity: 0.4 }} />
          </div>
        )}

        {isSidebarOpen && (
          <div style={{ width: sidebarWidth, minWidth: 320, height: '100%', flexShrink: 0, borderLeft: '1px solid var(--border-subtle)' }}>
            <div className={styles.sidebarContainer}>
              <div className={styles.sidebarTabs}>
                {(['messages', 'files', 'history'] as const).map((tab) => (
                  <button
                    key={tab}
                    onClick={() => setSidebarTab(tab)}
                    className={`${styles.tabButton} ${sidebarTab === tab ? styles.activeTab : ''}`}
                  >
                    {tab}
                  </button>
                ))}
              </div>

              <div style={{ flex: 1, overflow: "hidden", display: "flex", flexDirection: "column" }}>
                {sidebarTab === 'messages' && (
                  <>
                    <div className={styles.messageThread}>
                      {messages.map((m, i) => {
                        const isMe = m.sender_id === currentUser?.id || m.sender_role?.toLowerCase() === 'customer';
                        return (
                          <div key={i} className={`${styles.message} ${isMe ? styles.messageMe : styles.messageThem}`}>
                            <div className={styles.messageMeta}>
                              <span>{m.sender_name || 'Agent'}</span>
                              <span>{new Date(m.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}</span>
                              {isMe && (
                                <button
                                  onClick={() => handleDeleteMessage(m.id)}
                                  style={{ background: 'transparent', border: 'none', color: 'var(--error)', cursor: 'pointer', padding: 0, opacity: 0.5 }}
                                  title="Delete Message"
                                >
                                  <Trash2 size={11} />
                                </button>
                              )}
                            </div>
                            <div className={`${styles.messageBubble} ${isMe ? styles.messageBubbleMe : styles.messageBubbleThem}`}>
                              <div style={{ position: 'relative' }}>
                                <NexusMarkdown content={m.content} isMe={isMe} />
                                {m.is_sending && (
                                  <div className={styles.syncStatus}>
                                    <Loader2 size={10} className={styles.spin} />
                                    <span>SENDING...</span>
                                  </div>
                                )}
                              </div>
                            </div>
                          </div>
                        );
                      })}
                      <div ref={bottomRef} />
                    </div>

                    <div className={styles.replyConsole} style={{ position: 'relative' }}>
                      <div className={styles.replyArea}>
                        {showMentionList && (
                          <MentionOverlay
                            users={filteredUsers}
                            selectedIndex={selectedMentionIndex}
                            onSelect={handleInsertMention}
                            onClose={closeMentions}
                          />
                        )}
                        <textarea
                          value={newMessage}
                          onChange={handleMentionInput}
                          onPaste={(e) => handlePaste(e, false)}
                          onKeyDown={(e) => {
                            if (showMentionList && filteredUsers.length > 0) {
                              if (e.key === 'ArrowDown') { e.preventDefault(); setSelectedMentionIndex(idx => (idx + 1) % filteredUsers.length); }
                              else if (e.key === 'ArrowUp') { e.preventDefault(); setSelectedMentionIndex(idx => (idx - 1 + filteredUsers.length) % filteredUsers.length); }
                              else if (e.key === 'Enter' || e.key === 'Tab') { e.preventDefault(); handleInsertMention(filteredUsers[selectedMentionIndex]); }
                              else if (e.key === 'Escape') { closeMentions(); }
                            }
                          }}
                          placeholder="Reply to thread..."
                          className={styles.replyTextarea}
                        />

                        <button
                          onClick={handleSend}
                          disabled={sending || !newMessage.trim() || isUploading}
                          className={styles.sendBtnSmall}
                          title="Send Message"
                        >
                          {sending ? <Loader2 size={14} className={styles.spin} /> : <Send size={14} />}
                        </button>
                      </div>
                      <div className={styles.consoleFooter}>
                        <div className={styles.toolGroup}>
                          <button onClick={() => fileInputRef.current?.click()} disabled={isUploading} className={styles.toolBtn}>
                            <Paperclip size={14} />
                          </button>
                          <input type="file" ref={fileInputRef} onChange={e => e.target.files?.[0] && handleUpload(e.target.files[0], false)} style={{ display: 'none' }} />
                        </div>
                      </div>
                    </div>
                  </>
                )}

                {sidebarTab === 'files' && (
                  <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 12, background: 'var(--bg-dark)', flex: 1, overflowY: 'auto' }}>
                    {(ticket.attachments || []).map((att) => (
                      <div key={att.id} style={{ padding: '16px 20px', borderRadius: 12, background: '#fff', border: '1px solid var(--border-subtle)', display: 'flex', alignItems: 'center', gap: 16, boxShadow: '0 2px 8px rgba(0,0,0,0.02)' }}>
                        <div style={{ color: 'var(--primary)', background: 'var(--primary-glow)', width: 32, height: 32, borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                          {getFileIcon(att.filename)}
                        </div>
                        <div style={{ flex: 1, minWidth: 0, cursor: 'pointer' }} onClick={() => handleFileDownload(att.id, att.filename)}>
                          <div style={{ fontSize: 13, fontWeight: 800, color: 'var(--text-main)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{att.filename}</div>
                          <div style={{ fontSize: 10, color: 'var(--text-muted)', fontWeight: 600 }}>{(att.file_size / 1024).toFixed(1)} KB</div>
                        </div>
                        <div style={{ display: 'flex', gap: 4 }}>
                          <button 
                            onClick={() => handleFileDownload(att.id, att.filename)} 
                            className={styles.downloadBtn}
                            title="Download Asset"
                          >
                            <Download size={14} />
                          </button>
                          <button 
                            onClick={() => handleDeleteAttachment(att.id)} 
                            className={styles.deleteBtn}
                            title="Delete Asset"
                          >
                            <Trash2 size={14} />
                          </button>
                        </div>
                      </div>
                    ))}
                    {(ticket.attachments || []).length === 0 && (
                      <div style={{ textAlign: 'center', padding: 40, color: 'var(--text-muted)', fontSize: 12, fontWeight: 600 }}>No digital assets captured in this thread.</div>
                    )}
                  </div>
                )}

                {sidebarTab === 'history' && (
                  <div className={styles.historyTimeline}>
                    {historyEvents.map((event) => (
                      <div key={event.id} className={styles.historyItem}>
                        <div className={styles.historyLine} />
                        <div className={styles.historyIcon}>{event.icon}</div>
                        <div className={styles.historyContent}>
                          <div className={styles.historyMeta}>
                            <span className={styles.historyLabel}>{event.label}</span>
                            <span className={styles.historyTime}>{new Date(event.time).toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })}</span>
                          </div>
                          <div className={styles.historyDetail}>{event.detail}</div>
                        </div>
                      </div>
                    ))}
                    {historyEvents.length === 0 && (
                      <div style={{ textAlign: 'center', padding: 40, color: 'var(--text-muted)', fontSize: 12, fontWeight: 600 }}>No operational events recorded.</div>
                    )}
                  </div>
                )}
              </div>
            </div>
          </div>
        )}
      </div>

      {showReopenModal && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(8px)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
          <div className="organic-surface" style={{ width: '100%', maxWidth: 440, padding: 32, borderRadius: 12, boxShadow: '0 30px 60px rgba(0,0,0,0.4)', border: '1px solid var(--border-subtle)' }}>
            <h3 style={{ fontSize: 20, fontWeight: 900, marginBottom: 8, color: 'var(--text-main)', fontFamily: 'var(--font-heading)', letterSpacing: '-0.02em' }}>Reopen Ticket</h3>
            <p style={{ fontSize: 14, color: 'var(--text-muted)', lineHeight: 1.5, marginBottom: 24, opacity: 0.8 }}>Please provide a brief justification to resume this resolution.</p>
            <textarea
              autoFocus
              value={reopenReason}
              onChange={e => setReopenReason(e.target.value)}
              placeholder="Reason for reopening..."
              style={{
                width: "100%",
                padding: 16,
                borderRadius: 8,
                background: 'var(--bg-dark)',
                border: '1.5px solid var(--border-subtle)',
                fontSize: 14,
                color: 'var(--text-main)',
                marginBottom: 24,
                minHeight: 120,
                resize: 'none',
                outline: 'none',
                fontFamily: 'inherit'
              }}
            />
            <div style={{ display: 'flex', gap: 12 }}>
              <button onClick={() => setShowReopenModal(false)} className={styles.btnSecondary} style={{ flex: 1, height: 48 }}>CANCEL</button>
              <button onClick={handleReopen} disabled={!reopenReason.trim() || isReopening} className={styles.btnPrimary} style={{ flex: 1, height: 48 }}>
                {isReopening ? 'REOPENING...' : 'RESUME TICKET'}
              </button>
            </div>
          </div>
        </div>
      )}

      {showConfirmEscalate && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(12px)', zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
          <div className="organic-surface" style={{ maxWidth: 400, width: '100%', padding: 48, textAlign: 'center', borderRadius: 24, border: '1px solid var(--border-subtle)', boxShadow: 'var(--shadow-xl)' }}>
            <div style={{ fontSize: 64, marginBottom: 24, display: 'flex', justifyContent: 'center' }}>🚨</div>
            <h2 style={{ fontSize: 24, fontWeight: 900, marginBottom: 12, color: 'var(--text-main)', letterSpacing: '-0.02em' }}>CONFIRM ESCALATION</h2>
            <p style={{ fontSize: 15, color: 'var(--text-muted)', lineHeight: 1.6, marginBottom: 40, opacity: 0.9 }}>This will immediately notify lead specialists for priority intervention.</p>
            <div style={{ display: 'flex', gap: 16 }}>
              <button onClick={() => setShowConfirmEscalate(false)} className={styles.btnSecondary} style={{ flex: 1, height: 52 }}>CANCEL</button>
              <button onClick={handleEscalate} disabled={isEscalating} className={styles.btnPrimary} style={{ flex: 1, height: 52, background: 'var(--error)', boxShadow: '0 8px 20px rgba(239, 68, 68, 0.25)' }}>
                {isEscalating ? 'ESCALATING...' : 'CONFIRM'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};