Spaces:
Paused

File size: 36,684 Bytes
5eb4857
 
428a35c
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
428a35c
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
0d8550d
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d8550d
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d8550d
5eb4857
 
 
 
 
 
 
 
 
 
 
 
0d8550d
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
0d8550d
5eb4857
 
 
 
 
 
 
 
 
 
0d8550d
5eb4857
 
 
0d8550d
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
0d8550d
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
428a35c
5eb4857
428a35c
 
5eb4857
 
 
 
428a35c
5eb4857
428a35c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
428a35c
 
 
 
 
 
 
 
 
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
428a35c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
accf280
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94b1a89
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
428a35c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import React, { useState, useEffect, useRef } from 'react';
import { StatusBadge, PriorityBadge } from './Badges';
import { api, NexusMarkdown, getFileIcon } from '@nexus/shared';

const COLORS = {
  brand: "#1E40AF",
  brandLight: "#EFF6FF",
  gray50: "#F9FAFB",
  gray100: "#F3F4F6",
  gray200: "#E5E7EB",
  gray300: "#D1D5DB",
  gray400: "#9CA3AF",
  gray600: "#4B5563",
  gray700: "#374151",
  gray800: "#1F2937",
  gray900: "#111827",
  success: "#059669",
  warning: "#D97706",
  error: "#DC2626",
  indigo600: "#4F46E5",
  indigo50: "#EEF2FF",
};

interface ThreadViewProps {
  ticket: any;
  onBack: () => void;
  onNavigate?: (ticket: any) => void;
}

export const ThreadView: React.FC<ThreadViewProps> = ({ ticket: initialTicket, onBack, onNavigate }) => {
  const [ticket, setTicket] = useState(initialTicket);
  const [messages, setMessages] = useState<any[]>([]);
  const [newMessage, setNewMessage] = useState("");
  const [loading, setLoading] = useState(true);
  const [sending, setSending] = useState(false);
  
  // 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 [showConfirmEscalate, setShowConfirmEscalate] = useState(false);
  const [isEscalating, setIsEscalating] = useState(false);

  // Message Edit State
  const [editingMsgId, setEditingMsgId] = useState<string | null>(null);
  const [msgEditDraft, setMsgEditDraft] = useState("");

  const bottomRef = useRef<HTMLDivElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const descFileInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    refreshData();
  }, [initialTicket.id]);

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

  const refreshData = async () => {
    setLoading(true);
    try {
      const [ticketResp, messagesResp] = await Promise.all([
        api.get(`tickets/${initialTicket.id}/`),
        api.get(`tickets/${initialTicket.id}/messages/`)
      ]);
      setTicket(ticketResp.data);
      setDescDraft(ticketResp.data.description);
      setMessages(messagesResp.data);
    } catch (err) {
      console.error("Failed to refresh data:", err);
    } finally {
      setLoading(false);
    }
  };

  const handleSend = async () => {
    if (!newMessage.trim()) return;
    setSending(true);
    try {
      const resp = await api.post(`tickets/${ticket.id}/messages/`, { 
        content: newMessage, 
        is_internal: false 
      });
      setMessages([...messages, resp.data]);
      setNewMessage("");
    } catch (err) {
      console.error("Failed to send message:", err);
    } finally {
      setSending(false);
    }
  };

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

  const handleDeleteMessage = async (msgId: string) => {
    if (!window.confirm("Delete this message?")) return;
    try {
      await api.delete(`tickets/${ticket.id}/messages/${msgId}/`);
      setMessages(messages.filter(m => m.id !== msgId));
    } catch (err) {
      console.error("Failed to delete message:", err);
    }
  };

  const startEditMessage = (msg: any) => {
    setEditingMsgId(msg.id);
    setMsgEditDraft(msg.content);
  };

  const handleUpdateMessage = async (msgId: string) => {
    try {
      const resp = await api.patch(`tickets/${ticket.id}/messages/${msgId}/`, { content: msgEditDraft });
      setMessages(messages.map(m => m.id === msgId ? resp.data : m));
      setEditingMsgId(null);
    } catch (err) {
      console.error("Failed to update message:", err);
    }
  };

  const handleEscalate = async () => {
    setIsEscalating(true);
    try {
      const resp = await api.post(`tickets/${ticket.id}/escalate/`);
      setTicket(resp.data);
      setShowConfirmEscalate(false);
      // Refresh messages to show the system notification
      const messagesResp = await api.get(`tickets/${ticket.id}/messages/`);
      setMessages(messagesResp.data);
    } catch (err) {
      console.error("Escalation failed:", err);
      alert("Failed to escalate ticket. It might already be escalated.");
    } 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 });
      alert("Thank you for your feedback!");
    } catch (err) {
      console.error("Feedback submission failed:", err);
      alert("Failed to submit feedback.");
    } finally {
      setIsSubmittingFeedback(false);
    }
  };

  const handlePaste = async (e: React.ClipboardEvent, 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) => {
    setIsUploading(true);
    const formData = new FormData();
    formData.append("file", file);

    const isImage = file.type.startsWith("image/");
    const placeholder = isImage 
        ? `\n![Uploading ${file.name}...]()\n`
        : `\n[Uploading ${file.name}...]()\n`;

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

    try {
        const resp = await api.post(`tickets/upload/`, formData, {
            headers: { 'Content-Type': 'multipart/form-data' }
        });

        const backendBase = api.defaults.baseURL?.endsWith('/') ? api.defaults.baseURL : api.defaults.baseURL + '/';
        const downloadUrl = `${backendBase}tickets/attachments/${resp.data.id}/download/`;
        
        let finalMarkdown = "";
        if (isImage) {
            finalMarkdown = `\n![Screenshot](${downloadUrl})\n`;
        } else {
            const icon = getFileIcon(file.name);
            finalMarkdown = `\n${icon} [${file.name}](${downloadUrl})\n`;
        }
        
        if (isMainDesc) setDescDraft((curr: string) => curr.replace(placeholder, finalMarkdown));
        else setNewMessage((curr: string) => curr.replace(placeholder, finalMarkdown));
    } catch (err) {
        console.error("Upload failed:", err);
        alert("Failed to upload file.");
        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 "TBD";
    const date = new Date(dateStr);
    return date.toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
  };

  return (
    <div style={{ display: "flex", flexDirection: "column", height: "calc(100vh - 60px)", background: "#fff" }}>
      {/* Universal Sticky Header */}
      <div style={{ padding: "12px 32px", borderBottom: `1px solid ${COLORS.gray200}`, background: "#fff", display: "flex", alignItems: "center", gap: 16 }}>
        <button onClick={onBack} style={{ background: "none", border: `1px solid ${COLORS.gray200}`, borderRadius: 8, padding: "6px 14px", fontSize: 13, cursor: "pointer", color: COLORS.gray600, fontWeight: 500 }}>← Back</button>
        <div style={{ flex: 1 }}>
          <h1 style={{ fontSize: 16, fontWeight: 700, margin: 0, color: COLORS.gray900 }}>{ticket.title}</h1>
          <div style={{ display: "flex", gap: 10, alignItems: "center", marginTop: 4 }}>
            <span style={{ fontSize: 11, color: COLORS.gray400, fontFamily: "monospace", background: COLORS.gray50, padding: "2px 6px", borderRadius: 4 }}>{ticket.id.slice(0, 8)}</span>
            <StatusBadge status={ticket.status} />
            <PriorityBadge priority={ticket.priority} />
            {ticket.is_escalated && (
              <span style={{ 
                background: "#FEF2F2", 
                color: "#EF4444", 
                fontSize: 10, 
                fontWeight: 800, 
                padding: "2px 8px", 
                borderRadius: 4, 
                border: "1px solid #FEE2E2",
                animation: "pulse 2s infinite"
              }}>
                🚨 ESCALATED
              </span>
            )}
          </div>
        </div>
      </div>

      <div style={{ display: "flex", flex: 1, overflow: "hidden" }}>
        {/* Left Pane: Ticket Context (65%) */}
        <div style={{ flex: 1.8, overflowY: "auto", padding: "32px", borderRight: `1px solid ${COLORS.gray200}`, background: "#fff" }}>
          
          {/* AI Assessment Card */}
          {ticket.summary && (
            <div style={{ 
              background: "linear-gradient(135deg, #F5F7FF 0%, #FAF9FF 100%)", 
              borderRadius: 16, 
              border: "1px solid #DDE4FF", 
              padding: "24px",
              marginBottom: "32px",
              boxShadow: "0 4px 12px rgba(30, 64, 175, 0.03)"
            }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 12 }}>
                <span style={{ fontSize: 20 }}>πŸͺ„</span>
                <h3 style={{ fontSize: 13, fontWeight: 800, margin: 0, color: COLORS.brand, textTransform: "uppercase", letterSpacing: "0.1em" }}>AI Intelligence Summary</h3>
              </div>
              <p style={{ fontSize: 15, color: "#374151", lineHeight: 1.7, margin: 0 }}>
                {ticket.summary}
              </p>
            </div>
          )}
          {/* Ticket Insights Grid */}
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 20, marginBottom: 32 }}>
            <div style={{ padding: 16, border: `1px solid ${COLORS.gray100}`, borderRadius: 12, background: COLORS.gray50 }}>
              <div style={{ fontSize: 11, fontWeight: 800, color: COLORS.gray400, textTransform: "uppercase", marginBottom: 6 }}>Priority Detail</div>
              <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                <span style={{ 
                  width: 8, height: 8, borderRadius: "50%", 
                  background: ticket.priority === "P0" ? COLORS.error : ticket.priority === "P1" ? COLORS.warning : COLORS.brand 
                }} />
                <div style={{ fontSize: 13, fontWeight: 600, color: COLORS.gray900 }}>{ticket.priority} Β· {ticket.priority === 'P0' ? 'Critical' : 'Standard'}</div>
              </div>
            </div>
            <div style={{ padding: 16, border: `1px solid ${COLORS.gray100}`, borderRadius: 12, background: COLORS.gray50 }}>
              <div style={{ fontSize: 11, fontWeight: 800, color: COLORS.gray400, textTransform: "uppercase", marginBottom: 6 }}>Assignee</div>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <div style={{ width: 24, height: 24, borderRadius: "50%", background: COLORS.gray200, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 10, fontWeight: 700 }}>{ticket.assigned_name ? ticket.assigned_name[0] : "?"}</div>
                <div style={{ fontSize: 13, fontWeight: 600, color: COLORS.gray900 }}>{ticket.assigned_name || "Unassigned"}</div>
              </div>
            </div>
            <div style={{ padding: 16, border: `1px solid ${COLORS.gray100}`, borderRadius: 12, background: COLORS.gray50 }}>
              <div style={{ fontSize: 11, fontWeight: 800, color: COLORS.gray400, textTransform: "uppercase", marginBottom: 6 }}>Estimated Resolution</div>
              <div style={{ fontSize: 13, fontWeight: 600, color: COLORS.gray900 }}>{formatETA(ticket.expected_resolution_at)}</div>
            </div>
            <div style={{ padding: 16, border: `1px solid ${COLORS.gray100}`, borderRadius: 12, background: COLORS.gray50 }}>
              <div style={{ fontSize: 11, fontWeight: 800, color: COLORS.gray400, textTransform: "uppercase", marginBottom: 6 }}>Complexity</div>
              <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
                <span style={{ 
                  width: 8, height: 8, borderRadius: "50%", 
                  background: ticket.estimated_effort_hours?.complexity === "high" ? COLORS.error : ticket.estimated_effort_hours?.complexity === "medium" ? COLORS.warning : COLORS.success 
                }} />
                <div style={{ fontSize: 13, fontWeight: 600, color: COLORS.gray900, textTransform: "capitalize" }}>{ticket.estimated_effort_hours?.complexity || "Low"}</div>
              </div>
            </div>
          </div>

          {ticket.duplicate_of_id && (
            <div style={{ 
              marginBottom: 32, 
              padding: "24px", 
              background: "linear-gradient(135deg, #F3F4FB 0%, #F9FAFF 100%)", 
              borderRadius: 16, 
              border: "1px solid #DDE4FF", 
              display: "flex", 
              alignItems: "center", 
              justifyContent: "space-between",
              gap: 16,
              boxShadow: "0 4px 12px rgba(30, 64, 175, 0.03)"
            }}>
              <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
                <div style={{ width: 44, height: 44, borderRadius: 12, background: "#4F46E5", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 20, boxShadow: "0 4px 8px rgba(79, 70, 229, 0.2)" }}>πŸ“Ž</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 800, color: "#3730A3", textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: 4 }}>Duplicate Ticket Identified</div>
                  <p style={{ fontSize: 14, color: "#4338CA", margin: 0, lineHeight: 1.5 }}>
                    This case is a duplicate of <strong>{ticket.duplicate_of_title || ticket.duplicate_of_id}</strong>.
                  </p>
                </div>
              </div>
              <button 
                onClick={() => onNavigate && onNavigate({ id: ticket.duplicate_of_id })}
                style={{ background: "#4F46E5", color: "#fff", border: "none", borderRadius: 8, padding: "10px 16px", fontSize: 12, fontWeight: 700, cursor: "pointer", whiteSpace: "nowrap" }}
              >
                View Original Case β†’
              </button>
            </div>
          )}

          {/* Description Block */}
          <div style={{ background: COLORS.gray50, borderRadius: 16, padding: "24px", border: `1px solid ${COLORS.gray100}`, marginBottom: 32 }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
              <h3 style={{ fontSize: 14, fontWeight: 700, margin: 0, color: COLORS.gray800 }}>Issue Description</h3>
              {ticket.status !== 'closed' && (
                <button 
                  onClick={() => setIsEditingDesc(!isEditingDesc)}
                  style={{ background: "none", border: "none", color: COLORS.brand, fontSize: 13, fontWeight: 600, cursor: "pointer" }}
                >
                  {isEditingDesc ? "Cancel" : "Edit Details"}
                </button>
              )}
            </div>

            {isEditingDesc ? (
              <div>
                <textarea 
                  value={descDraft}
                  onChange={e => setDescDraft(e.target.value)}
                  onPaste={e => handlePaste(e, true)}
                  placeholder="Describe your issue..."
                  style={{ width: "100%", minHeight: 180, padding: 16, borderRadius: 12, border: `2px solid ${COLORS.brand}`, fontSize: 14, outline: "none", resize: "vertical", fontFamily: "inherit", background: "#fff" }}
                />
                <div style={{ marginTop: 12, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                  <button 
                    onClick={handleUpdateDescription}
                    disabled={savingDesc || isUploading}
                    style={{ padding: "8px 20px", background: COLORS.brand, color: "#fff", border: "none", borderRadius: 8, fontSize: 13, fontWeight: 600, cursor: "pointer" }}
                  >
                    {savingDesc ? "Updating..." : "Save Description"}
                  </button>
                  <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
                    {isUploading && <span style={{ fontSize: 12, color: COLORS.brand }}>Uploading file...</span>}
                    <button 
                      onClick={() => descFileInputRef.current?.click()}
                      style={{ background: "none", border: "none", color: COLORS.brand, fontSize: 13, fontWeight: 600, cursor: "pointer" }}
                    >
                      πŸ“Ž Attach
                    </button>
                    <input 
                      type="file" 
                      ref={descFileInputRef} 
                      onChange={(e) => e.target.files?.[0] && handleUpload(e.target.files[0], true)} 
                      style={{ display: "none" }} 
                    />
                  </div>
                </div>
              </div>
            ) : (
              <div style={{ fontSize: 15, color: COLORS.gray700, lineHeight: 1.8, overflowWrap: "anywhere", wordBreak: "break-word" }}>
                <NexusMarkdown content={ticket.description} />
              </div>
            )}
          </div>

          {ticket.is_escalated && (
            <div style={{ 
              marginBottom: 32, 
              padding: "24px", 
              background: "linear-gradient(135deg, #FEF2F2 0%, #FFF1F2 100%)", 
              borderRadius: 16, 
              border: "1px solid #FECACA", 
              display: "flex", 
              alignItems: "center", 
              gap: 16,
              boxShadow: "0 4px 12px rgba(239, 68, 68, 0.05)"
            }}>
              <div style={{ width: 44, height: 44, borderRadius: 12, background: "#EF4444", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 20, boxShadow: "0 4px 8px rgba(239, 68, 68, 0.2)" }}>🚨</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 800, color: "#991B1B", textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: 4 }}>Urgent Escalation Active</div>
                <p style={{ fontSize: 14, color: "#B91C1C", margin: 0, lineHeight: 1.5 }}>
                  This ticket has been escalated to <strong>{ticket.escalated_to_name || "Support Lead"}</strong>. 
                  <span style={{ display: "block", marginTop: 4, fontWeight: 600 }}>Resolution is prioritized by workspace leads.</span>
                </p>
              </div>
            </div>
          )}

          {!ticket.is_escalated && !['RESOLVED', 'CLOSED'].includes((ticket.status || '').toUpperCase()) && (
            <div style={{ marginBottom: 32, padding: 20, background: showConfirmEscalate ? "#FFF1F2" : "#FFF1F2", borderRadius: 16, border: `1px solid ${showConfirmEscalate ? "#EF4444" : "#FFE4E6"}`, display: "flex", justifyContent: "space-between", alignItems: "center", transition: "all 0.2s" }}>
              <div style={{ flex: 1 }}>
                <h4 style={{ fontSize: 14, fontWeight: 700, color: "#9F1239", margin: "0 0 4px 0" }}>
                  {showConfirmEscalate ? "⚠️ Confirm Manual Escalation" : "Need faster resolution?"}
                </h4>
                <p style={{ fontSize: 12, color: "#BE123C", margin: 0 }}>
                  {showConfirmEscalate 
                    ? "This action is irreversible. All support leads will be notified immediately." 
                    : "Escalating this ticket will alert support leads and set priority to P0."}
                </p>
              </div>
              
              <div style={{ display: "flex", gap: 10 }}>
                {showConfirmEscalate ? (
                  <>
                    <button 
                      onClick={() => setShowConfirmEscalate(false)}
                      disabled={isEscalating}
                      style={{ background: "#fff", color: "#6B7280", border: "1px solid #D1D5DB", borderRadius: 8, padding: "10px 16px", fontSize: 13, fontWeight: 600, cursor: "pointer" }}
                    >
                      Cancel
                    </button>
                    <button 
                      onClick={handleEscalate}
                      disabled={isEscalating}
                      style={{ background: "#EF4444", color: "#fff", border: "none", borderRadius: 8, padding: "10px 20px", fontSize: 13, fontWeight: 700, cursor: isEscalating ? "default" : "pointer", boxShadow: "0 4px 12px rgba(239, 68, 68, 0.2)" }}
                    >
                      {isEscalating ? "Escalating..." : "Yes, Escalate Now"}
                    </button>
                  </>
                ) : (
                  <button 
                    onClick={() => setShowConfirmEscalate(true)}
                    style={{ background: "#E11D48", color: "#fff", border: "none", borderRadius: 8, padding: "10px 20px", fontSize: 13, fontWeight: 700, cursor: "pointer", boxShadow: "0 4px 12px rgba(225, 29, 72, 0.2)" }}
                  >
                    Escalate Issue
                  </button>
                )}
              </div>
            </div>
          )}

          {/* Related Help Articles */}
          {ticket.similar_articles && ticket.similar_articles.length > 0 && (
            <div style={{ marginBottom: 32 }}>
               <h3 style={{ fontSize: 14, fontWeight: 700, marginBottom: 16, color: COLORS.gray900, display: "flex", alignItems: "center", gap: 8 }}>
                 πŸ“š Related Help Articles
               </h3>
               <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
                 {ticket.similar_articles.map((art: any) => (
                   <a 
                    key={art.id} 
                    href={`/kb/${art.id}`} 
                    target="_blank" 
                    rel="noreferrer"
                    style={{ padding: "12px 16px", background: "#fff", border: `1px solid ${COLORS.gray200}`, borderRadius: 10, textDecoration: "none", display: "flex", justifyContent: "space-between", alignItems: "center", transition: "all 0.2s" }}
                    onMouseEnter={e => e.currentTarget.style.borderColor = COLORS.brand}
                    onMouseLeave={e => e.currentTarget.style.borderColor = COLORS.gray200}
                   >
                     <span style={{ fontSize: 13, fontWeight: 500, color: COLORS.gray700 }}>{art.title}</span>
                     <span style={{ fontSize: 12, color: COLORS.brand }}>Read Article β†’</span>
                   </a>
                 ))}
               </div>
            </div>
          )}

          {/* Resolution Details Block */}
          {(ticket.status?.toUpperCase() === 'RESOLVED' || ticket.status?.toUpperCase() === 'CLOSED') && (
            <div style={{ 
              background: "#F0FDF4", 
              borderRadius: 16, 
              padding: "24px", 
              border: "1px solid #BBF7D0", 
              marginBottom: "32px",
              boxShadow: "0 4px 12px rgba(21, 128, 61, 0.04)"
            }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 16 }}>
                <div>
                  <h3 style={{ fontSize: 13, fontWeight: 800, margin: "0 0 4px 0", color: "#15803D", textTransform: "uppercase", letterSpacing: "0.1em" }}>βœ… Official Resolution Details</h3>
                  <div style={{ fontSize: 12, color: "#166534", opacity: 0.8 }}>
                    Resolved by <strong>{ticket.resolved_by_name || "Nexus Agent"}</strong> β€’ {formatETA(ticket.resolved_at)}
                  </div>
                </div>
                <div style={{ background: "#DCFCE7", color: "#166534", padding: "4px 12px", borderRadius: "100px", fontSize: 11, fontWeight: 800 }}>FINAL OUTCOME</div>
              </div>
              
              <div style={{ 
                fontSize: 15, 
                color: "#14532D", 
                lineHeight: 1.7, 
                background: "#fff", 
                padding: "20px", 
                borderRadius: 12, 
                border: "1px solid #DCFCE7",
                overflowWrap: "anywhere",
                wordBreak: "break-word"
              }}>
                <NexusMarkdown content={ticket.resolution_text || "No resolution text provided."} />
              </div>

              {/* Feedback Section */}
              <div style={{ marginTop: 20, paddingTop: 20, borderTop: "1px dashed #BBF7D0" }}>
                {ticket.rating ? (
                  <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                    <div style={{ fontSize: 13, fontWeight: 700, color: "#15803D" }}>Your Rating:</div>
                    <div style={{ display: "flex", gap: 2 }}>
                      {[1, 2, 3, 4, 5].map(star => (
                        <span key={star} style={{ fontSize: 18, color: star <= ticket.rating ? "#D97706" : "#E5E7EB" }}>β˜…</span>
                      ))}
                    </div>
                  </div>
                ) : (
                  <div>
                    <div style={{ fontSize: 13, fontWeight: 700, color: "#15803D", marginBottom: 12 }}>How was your experience?</div>
                    <div style={{ display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
                      <div style={{ display: "flex", gap: 4 }}>
                        {[1, 2, 3, 4, 5].map(star => (
                          <button
                            key={star}
                            onMouseEnter={() => setHoverRating(star)}
                            onMouseLeave={() => setHoverRating(null)}
                            onClick={() => setRatingDraft(star)}
                            style={{ 
                              background: "none", border: "none", padding: 0, cursor: "pointer", fontSize: 24,
                              color: star <= (hoverRating || ratingDraft || 0) ? "#D97706" : "#E5E7EB",
                              transition: "transform 0.1s"
                            }}
                          >
                            β˜…
                          </button>
                        ))}
                      </div>
                      <input 
                        placeholder="Add an optional comment..."
                        value={commentDraft}
                        onChange={(e) => setCommentDraft(e.target.value)}
                        style={{ flex: 1, minWidth: 200, padding: "8px 12px", borderRadius: 8, border: "1px solid #BBF7D0", fontSize: 13 }}
                      />
                      <button
                        onClick={handleSubmitFeedback}
                        disabled={!ratingDraft || isSubmittingFeedback}
                        style={{ 
                          background: ratingDraft ? "#15803D" : "#E5E7EB", 
                          color: "#fff", border: "none", borderRadius: 8, padding: "8px 16px", fontSize: 13, fontWeight: 700, 
                          cursor: ratingDraft ? "pointer" : "default" 
                        }}
                      >
                        {isSubmittingFeedback ? "Saving..." : "Submit Feedback"}
                      </button>
                    </div>
                  </div>
                )}
              </div>
            </div>
          )}
        </div>

        {/* Right Pane: Activity Feed (35%) */}
        <div style={{ flex: 1, display: "flex", flexDirection: "column", background: COLORS.gray50 }}>
          <div style={{ flex: 1, overflowY: "auto", padding: "24px" }}>
            <div style={{ fontSize: 11, fontWeight: 800, color: COLORS.gray400, textTransform: "uppercase", letterSpacing: "0.1em", marginBottom: 20, textAlign: "center" }}>Activity History</div>
            
            {loading ? (
              <div style={{ textAlign: "center", color: COLORS.gray400, marginTop: 40 }}>Loading thread...</div>
            ) : messages.map((msg: any) => {
              const isMe = msg.sender_role?.toLowerCase() === 'customer' || !msg.sender_role;
              const isAI = msg.sender_role === "nexus_ai";
              
              return (
                <div key={msg.id} style={{ marginBottom: 24, display: "flex", flexDirection: isMe ? "row-reverse" : "row", gap: 12 }}>
                  <div style={{ 
                    width: 36, height: 36, borderRadius: "50%", 
                    background: isMe ? COLORS.brand : isAI ? "#EDE9FE" : "#FDE68A", 
                    flexShrink: 0, display: "flex", alignItems: "center", justifyContent: "center", 
                    fontSize: 11, fontWeight: 800, color: isMe ? "#fff" : isAI ? "#6D28D9" : "#92400E",
                    boxShadow: "0 2px 4px rgba(0,0,0,0.05)"
                  }}>
                    {isMe ? "YOU" : isAI ? "AI" : "AG"}
                  </div>
                  
                  <div style={{ maxWidth: "80%", display: "flex", flexDirection: "column", alignItems: isMe ? "flex-end" : "flex-start" }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4, flexDirection: isMe ? "row-reverse" : "row" }}>
                      <span style={{ fontSize: 11, fontWeight: 700, color: COLORS.gray600 }}>{isMe ? "You" : isAI ? "Nexus AI" : msg.sender_name}</span>
                      <span style={{ fontSize: 10, color: COLORS.gray400 }}>{new Date(msg.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}</span>
                      
                      {isMe && !isAI && (
                        <div style={{ display: "flex", gap: 6 }}>
                           <button onClick={() => startEditMessage(msg)} style={{ background: "none", border: "none", fontSize: 10, color: COLORS.brand, cursor: "pointer", padding: 0 }}>Edit</button>
                           <button onClick={() => handleDeleteMessage(msg.id)} style={{ background: "none", border: "none", fontSize: 10, color: "#EF4444", cursor: "pointer", padding: 0 }}>Delete</button>
                        </div>
                      )}
                    </div>

                    {editingMsgId === msg.id ? (
                      <div style={{ width: "100%" }}>
                        <textarea 
                          value={msgEditDraft}
                          onChange={e => setMsgEditDraft(e.target.value)}
                          style={{ width: "100%", padding: 10, borderRadius: 8, border: `1px solid ${COLORS.brand}`, fontSize: 13 }}
                        />
                        <div style={{ display: "flex", gap: 6, marginTop: 4 }}>
                          <button onClick={() => handleUpdateMessage(msg.id)} style={{ padding: "4px 10px", background: COLORS.brand, color: "#fff", border: "none", borderRadius: 4, fontSize: 11 }}>Update</button>
                          <button onClick={() => setEditingMsgId(null)} style={{ padding: "4px 10px", background: COLORS.gray200, border: "none", borderRadius: 4, fontSize: 11 }}>Cancel</button>
                        </div>
                      </div>
                    ) : (
                      <div style={{ 
                        background: isMe ? COLORS.brand : "#fff", 
                        color: isMe ? "#fff" : COLORS.gray800, 
                        padding: "12px 18px", 
                        borderRadius: isMe ? "18px 2px 18px 18px" : "2px 18px 18px 18px",
                        fontSize: 14,
                        lineHeight: 1.6,
                        boxShadow: isMe ? "0 4px 12px rgba(30, 64, 175, 0.15)" : "0 1px 3px rgba(0,0,0,0.08)",
                        border: isMe ? "none" : `1px solid ${COLORS.gray200}`,
                        overflowWrap: "anywhere",
                        wordBreak: "break-word"
                      }}>
                        <NexusMarkdown content={msg.content} isMe={isMe} />
                      </div>
                    )}
                  </div>
                </div>
              );
            })}
            <div ref={bottomRef} />
          </div>

          {/* Fixed Reply Console */}
          <div style={{ padding: "20px", background: "#fff", borderTop: `1px solid ${COLORS.gray200}`, position: "relative" }}>
            
            {/* Floating Intelligence Notice */}
            {ticket.assigned_name && (
              <div style={{ 
                position: "absolute", 
                top: -36, 
                left: 20, 
                right: 20, 
                background: "rgba(255, 251, 235, 0.95)", 
                backdropFilter: "blur(4px)",
                border: "1px solid rgba(251, 191, 36, 0.3)", 
                borderRadius: "8px 8px 0 0", 
                padding: "6px 16px",
                display: "flex",
                alignItems: "center",
                gap: 8,
                zIndex: 5,
                boxShadow: "0 -4px 12px rgba(0, 0, 0, 0.03)"
              }}>
                <span style={{ fontSize: 12, animation: "bounce 2s infinite" }}>🧬</span>
                <span style={{ fontSize: 11, fontWeight: 700, color: "#B45309", letterSpacing: "0.02em" }}>
                  {ticket.assigned_name} will reply asap. Please wait!
                </span>
                <div style={{ 
                  flex: 1, 
                  height: 2, 
                  background: "linear-gradient(90deg, #FDE68A 0%, #F59E0B 50%, #FDE68A 100%)",
                  backgroundSize: "200% auto",
                  animation: "branding-shimmer 3s infinite linear",
                  borderRadius: 1,
                  opacity: 0.6
                }} />
              </div>
            )}

            <div style={{ position: "relative" }}>
              <textarea 
                value={newMessage}
                onChange={e => setNewMessage(e.target.value)}
                onPaste={e => handlePaste(e, false)}
                style={{ width: "100%", minHeight: 100, padding: "16px", borderRadius: 12, border: `1px solid ${COLORS.gray200}`, fontSize: 13, outline: "none", resize: "none", background: COLORS.gray50, fontFamily: "inherit" }}
              />
              <div style={{ position: "absolute", right: 12, bottom: 12, display: 'flex', gap: 8, alignItems: 'center' }}>
                <button 
                    onClick={() => fileInputRef.current?.click()}
                    disabled={isUploading}
                    style={{ background: "none", border: "none", cursor: "pointer", fontSize: 18, color: COLORS.gray400, padding: "4px" }}
                    title="Attach file"
                >
                    πŸ“Ž
                </button>
                <input 
                    type="file" 
                    ref={fileInputRef} 
                    onChange={(e) => e.target.files?.[0] && handleUpload(e.target.files[0], false)} 
                    style={{ display: "none" }} 
                />
                <button 
                    onClick={handleSend}
                    disabled={!newMessage.trim() || sending || isUploading}
                    style={{ padding: "8px 16px", background: newMessage.trim() ? COLORS.brand : COLORS.gray300, color: "#fff", border: "none", borderRadius: 8, fontSize: 12, fontWeight: 700, cursor: newMessage.trim() ? "pointer" : "default" }}
                >
                    {sending ? "..." : "Send"}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};