File size: 29,689 Bytes
ffcad5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fbe4a1
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
import React, { useState, useEffect } from 'react';
import {
  MessageSquare,
  SquarePen,
  Search,
  MoreVertical,
  Trash2,
  LogOut,
  User,
  UserCircle,
  DatabaseZap,
  KeyRound,
  PanelLeft,
  FileText,
  ChevronRight,
  Clock,
  Activity,
  Map,
  Eraser,
  Sun,
  Moon,
  Monitor,
  Check,
  BookOpen,
} from 'lucide-react';
import * as LucideIcons from 'lucide-react';
import { useAppConfig } from '../contexts/AppConfigContext';
import { useTheme } from '../contexts/ThemeContext';
import UserAvatarPicker from './UserAvatarPicker';
import CopyrightNotice from './CopyrightNotice';
import '../styles/Sidebar.css';

const APPEARANCE_OPTIONS = [
  { value: 'system', label: 'System', Icon: Monitor },
  { value: 'light', label: 'Light', Icon: Sun },
  { value: 'dark', label: 'Dark', Icon: Moon },
];

const Sidebar = ({

  user,

  currentSessionId,

  onSelectSession,

  onNewChat,

  onSignOut,

  authToken,

  onSidebarToggle,

  isMobileOpen = false,

  onMobileToggle,

  refreshTrigger,

  onCurrentSessionDeleted,

  pageContext = 'chat',

  canvasItems = [],

  canvasSubview = 'workspace',

  widgetGroups = [],

  deliverableProjects = [],

  insightSections = [],

  userAvatarId,

  onAvatarChange,

  onOpenProfile,

  onOpenAccount,

  onOpenClearData,

  onOpenModelStatus,

  onNavigateToJourney,

  onRemoveSampleData,

}) => {
  const { config } = useAppConfig();
  const { preference, setThemePreference } = useTheme();
  const isOnCanvas = pageContext === 'canvas';
  const isOnJourney = pageContext === 'journey';
  const isGuest = Boolean(user?.is_guest);
  const guestStyleLabel = (() => {
    if (!isGuest) return null;
    const stored = (user?.guest_label || '').trim();
    if (stored) return stored.charAt(0).toUpperCase() + stored.slice(1).toLowerCase();
    const persona = (user?.guest_persona || '').toLowerCase();
    if (persona === 'personal') return 'Personal';
    if (persona === 'business') return 'Business';
    if (persona === 'other') return 'Custom';
    return 'Guest';
  })();
  const [showAvatarPicker, setShowAvatarPicker] = useState(false);
  const avatarOptions = config?.app?.user_avatars || [];
  const currentAvatar = avatarOptions.find(a => a.id === userAvatarId);
  const AvatarIcon = currentAvatar ? (LucideIcons[currentAvatar.icon] || User) : User;
  const [expanded, setExpanded] = useState(() => {
    try { return JSON.parse(localStorage.getItem('sidebar-expanded-v1') || '{}'); } catch { return {}; }
  });
  const toggleExpanded = (key) => {
    setExpanded(prev => {
      const next = { ...prev, [key]: !prev[key] };
      localStorage.setItem('sidebar-expanded-v1', JSON.stringify(next));
      return next;
    });
  };
  const [chatSessions, setChatSessions] = useState([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [isLoading, setIsLoading] = useState(true);
  const [showUserMenu, setShowUserMenu] = useState(false);
  const [showAppearanceMenu, setShowAppearanceMenu] = useState(false);
  const [isCollapsed, setIsCollapsed] = useState(false);
  const [isCreatingNewChat, setIsCreatingNewChat] = useState(false);

  useEffect(() => {
    if (authToken) {
      fetchChatSessions();
    }
  }, [authToken]);

  useEffect(() => {
    const handleOverlayClick = (e) => {
      // Only close if clicking the overlay itself, not the sidebar
      if (e.target.classList.contains('mobile-sidebar-overlay')) {
        onMobileToggle(false);
      }
    };

    if (isMobileOpen) {
      document.addEventListener('click', handleOverlayClick);
      return () => document.removeEventListener('click', handleOverlayClick);
    }
  }, [isMobileOpen, onMobileToggle]);

  // Notify parent when sidebar state changes
  useEffect(() => {
    if (onSidebarToggle) {
      onSidebarToggle(isCollapsed);
    }
  }, [isCollapsed, onSidebarToggle]);

  // Add effect to refresh when currentSessionId changes (new session created)
  useEffect(() => {
    if (currentSessionId && authToken) {
      // Small delay to ensure the session is saved to database
      const timer = setTimeout(() => {
        fetchChatSessions();
      }, 200);
      return () => clearTimeout(timer);
    }
  }, [currentSessionId, authToken]);

  // Refresh session list when parent signals a message exchange completed
  useEffect(() => {
    if (refreshTrigger > 0 && authToken) {
      fetchChatSessions();
    }
  }, [refreshTrigger]);


  const fetchChatSessions = async () => {
    try {
      const response = await fetch(`${process.env.REACT_APP_API_URL}/api/chat-sessions`, {
        headers: {
          'Authorization': `Bearer ${authToken}`,
          'Content-Type': 'application/json'
        }
      });

      if (response.ok) {
        const sessions = await response.json();
        setChatSessions(sessions);
      } else {
        console.error('Failed to fetch chat sessions');
      }
    } catch (error) {
      console.error('Error fetching chat sessions:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const handleNewChat = async () => {
    setIsCreatingNewChat(true);
    
    try {
      // Call the parent's new chat handler and wait for it to complete
      await onNewChat();
      
      // Refresh the sessions list immediately after new chat is created
      // The parent should have updated currentSessionId by now
      await fetchChatSessions();
      
    } catch (error) {
      console.error('Error creating new chat:', error);
      // Optionally show an error message to the user
    } finally {
      setIsCreatingNewChat(false);
    }
  };

  const handleDeleteSession = async (sessionId, event) => {
    event.stopPropagation();
    
    if (window.confirm('Are you sure you want to delete this chat?')) {
      try {
        const response = await fetch(`${process.env.REACT_APP_API_URL}/api/chat-sessions/${sessionId}`, {
          method: 'DELETE',
          headers: {
            'Authorization': `Bearer ${authToken}`,
            'Content-Type': 'application/json'
          }
        });

        if (response.ok) {
          setChatSessions(prev => prev.filter(session => session.id !== sessionId));
          if (currentSessionId === sessionId) {
            onCurrentSessionDeleted?.();
          }
        }
      } catch (error) {
        console.error('Error deleting chat session:', error);
      }
    }
  };

  const toggleSidebar = () => {
    setIsCollapsed(!isCollapsed);
    // Close user menu when collapsing
    if (!isCollapsed) {
      setShowUserMenu(false);
      setShowAppearanceMenu(false);
    }
  };

  const filteredSessions = chatSessions.filter(session =>
    session.title.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const formatDate = (dateString) => {
    const date = new Date(dateString);
    const now = new Date();
    const diffTime = Math.abs(now - date);
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

    if (diffDays === 1) return 'Today';
    if (diffDays === 2) return 'Yesterday';
    if (diffDays <= 7) return `${diffDays - 1} days ago`;
    return date.toLocaleDateString();
  };

  return (
    <>

      <div className={`sidebar ${isCollapsed ? 'collapsed' : ''} ${isMobileOpen ? 'mobile-open' : ''}`}>

        {/* Header */}

        <div className="sidebar-header">

          {!isCollapsed && (

            <>

              <div className="sidebar-brand" aria-label={config?.app?.title || 'Cybersecurity Advisor'}>

                <div className="sidebar-brand-mark" aria-hidden="true">

                  <img src="/brand/cybersecurity-advisor-mark.png" alt="" />

                </div>

                <div className="sidebar-brand-text">

                  <span className="sidebar-brand-title">

                    {config?.app?.title || 'Cybersecurity Advisor'}

                  </span>

                  {config?.app?.subtitle ? (

                    <span className="sidebar-brand-subtitle">{config.app.subtitle}</span>

                  ) : null}

                </div>

              </div>

              <div className="user-section">

                <div className="user-info">

                  <div

                    className="user-avatar"

                    onClick={() => onAvatarChange && setShowAvatarPicker(true)}

                    style={{

                      cursor: onAvatarChange ? 'pointer' : undefined,

                      backgroundColor: currentAvatar?.bg || undefined,

                      color: currentAvatar?.color || undefined,

                    }}

                    title={onAvatarChange ? 'Change avatar' : undefined}

                  >

                    <AvatarIcon size={20} />

                  </div>

                  <div className="user-details">

                    <span className="user-name">

                      {isGuest

                        ? `Guest Explorer · ${guestStyleLabel}`

                        : `${user.firstName} ${user.lastName}`}

                    </span>

                    <span className="user-email">

                      {isGuest ? 'Demo session — sample data loaded' : user.email}

                    </span>

                  </div>

                </div>

                

                <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>

                  {/* Toggle button next to user menu when expanded */}

                  <button 

                    className="sidebar-toggle"

                    onClick={toggleSidebar} 

                    title="Collapse sidebar"

                  >

                    <PanelLeft size={18} />

                  </button>

                  

                  <div className="user-menu-container">

                    <button 

                      className="user-menu-button"

                      onClick={() => {

                        setShowUserMenu(!showUserMenu);

                        setShowAppearanceMenu(false);

                      }}

                    >

                      <MoreVertical size={16} />

                    </button>

                    

                    {showUserMenu && (

                      <div className="user-menu">

                        <button className="user-menu-item" onClick={() => { setShowUserMenu(false); setShowAppearanceMenu(false); setShowAvatarPicker(true); }}>

                          <User size={16} />

                          <span>Change Avatar</span>

                        </button>

                        <button className="user-menu-item" onClick={() => { setShowUserMenu(false); setShowAppearanceMenu(false); if (onOpenProfile) onOpenProfile(); }}>

                          <UserCircle size={16} />

                          <span>About You</span>

                        </button>

                        <button

                          className="user-menu-item"

                          onClick={() => {

                            setShowUserMenu(false);

                            setShowAppearanceMenu(false);

                            window.dispatchEvent(new CustomEvent('open-user-guide'));

                          }}

                        >

                          <BookOpen size={16} />

                          <span>User Guide</span>

                        </button>

                        <button className="user-menu-item" onClick={() => { setShowUserMenu(false); setShowAppearanceMenu(false); if (onOpenAccount) onOpenAccount(); }}>

                          <KeyRound size={16} />

                          <span>Account</span>

                        </button>

                        <button className="user-menu-item" onClick={() => { setShowUserMenu(false); setShowAppearanceMenu(false); if (onOpenClearData) onOpenClearData(); }}>

                          <DatabaseZap size={16} />

                          <span>Clear User Data</span>

                        </button>

                        {isGuest && onRemoveSampleData && (

                          <button

                            className="user-menu-item"

                            onClick={() => { setShowUserMenu(false); setShowAppearanceMenu(false); onRemoveSampleData(); }}

                          >

                            <Eraser size={16} />

                            <span>Remove all sample data</span>

                          </button>

                        )}

                        {onOpenModelStatus && (

                          <button className="user-menu-item" onClick={() => { setShowUserMenu(false); setShowAppearanceMenu(false); onOpenModelStatus(); }}>

                            <Activity size={16} />

                            <span>Model Status</span>

                          </button>

                        )}

                        <div className="user-menu-appearance">

                          <button

                            className="user-menu-item"

                            onClick={() => setShowAppearanceMenu((open) => !open)}

                            aria-expanded={showAppearanceMenu}

                          >

                            {preference === 'dark' ? <Moon size={16} /> : preference === 'light' ? <Sun size={16} /> : <Monitor size={16} />}

                            <span>Appearance{preference === 'system' ? ' · System' : ''}</span>

                            <ChevronRight size={14} className={`appearance-chevron ${showAppearanceMenu ? 'open' : ''}`} />

                          </button>

                          {showAppearanceMenu && (

                            <div className="appearance-options" role="group" aria-label="Appearance">

                              {APPEARANCE_OPTIONS.map(({ value, label, Icon }) => (

                                <button

                                  key={value}

                                  type="button"

                                  className={`user-menu-item appearance-option ${preference === value ? 'active' : ''}`}

                                  onClick={() => {

                                    setThemePreference(value);

                                    setShowAppearanceMenu(false);

                                    setShowUserMenu(false);

                                  }}

                                >

                                  <Icon size={16} />

                                  <span>{label}</span>

                                  {preference === value && <Check size={14} className="appearance-check" />}

                                </button>

                              ))}

                            </div>

                          )}

                        </div>

                        <button className="user-menu-item sign-out" onClick={onSignOut}>

                          <LogOut size={16} />

                          <span>Sign Out</span>

                        </button>

                      </div>

                    )}

                  </div>

                </div>

              </div>



            </>

          )}



          {isCollapsed && (

            <div className="collapsed-header">

              <div

                className="sidebar-brand-mark collapsed-brand-mark"

                title={config?.app?.title || 'Cybersecurity Advisor'}

                aria-label={config?.app?.title || 'Cybersecurity Advisor'}

              >

                <img src="/brand/cybersecurity-advisor-mark.png" alt="" />

              </div>

              {/* Toggle button replaces user avatar when collapsed */}

              <button 

                className="collapsed-toggle-avatar"

                onClick={toggleSidebar} 

                title="Expand sidebar"

              >

                <PanelLeft size={20} />

              </button>

              <button

                className="collapsed-new-chat"

                onClick={handleNewChat}

                title="New Chat"

                disabled={isCreatingNewChat}

              >

                <SquarePen size={20} />

              </button>

              {onNavigateToJourney && (

                <button

                  className="collapsed-new-chat"

                  onClick={onNavigateToJourney}

                  title="Journey"

                >

                  <Map size={20} />

                </button>

              )}

            </div>

          )}

        </div>



        {/* Search + New Chat - only show when expanded */}

        {!isCollapsed && (

          <div className="sidebar-search">

            <div className="search-container">

              <Search size={16} className="search-icon" />

              <input

                type="text"

                placeholder={

                  isOnCanvas

                    ? (canvasSubview === 'deliverables' ? 'Search drafts...'

                       : canvasSubview === 'insights' ? 'Search sections...'

                       : 'Search widgets...')

                    : 'Search chats...'

                }

                value={searchTerm}

                onChange={(e) => setSearchTerm(e.target.value)}

                className="search-input"

              />

            </div>

            {!isOnCanvas && (

              <button

                className="new-chat-icon-btn"

                onClick={handleNewChat}

                disabled={isCreatingNewChat}

                title={isCreatingNewChat ? 'Creating...' : 'New Chat'}

              >

                <SquarePen size={18} />

              </button>

            )}

            {onNavigateToJourney && (

              <button

                className="new-chat-icon-btn"

                onClick={onNavigateToJourney}

                title="Journey"

                style={isOnJourney ? { color: 'var(--accent-primary)' } : undefined}

              >

                <Map size={18} />

              </button>

            )}

          </div>

        )}



        {/* Canvas sidebar — subview-aware (Insights / Workspace / Deliverables) */}

        {isOnCanvas ? (

          <div className="canvas-sidebar-menu">

            {!isCollapsed && (() => {

              const q = searchTerm.toLowerCase();



              // ---------- DELIVERABLES: project list with expandable section dropdown ----------

              if (canvasSubview === 'deliverables') {

                const projects = deliverableProjects.filter(p =>

                  !q || p.name.toLowerCase().includes(q) || p.sections.some(s => s.name.toLowerCase().includes(q))

                );

                if (projects.length === 0) {

                  return (

                    <div className="no-sessions">

                      {searchTerm ? 'No drafts match' : 'No drafts yet — create one in Documents'}

                    </div>

                  );

                }

                return projects.map(p => {

                  const open = expanded[`p-${p.id}`] ?? p.isActive;

                  const totalWords = p.sections.reduce((s, x) => s + x.wc, 0);

                  return (

                    <div key={p.id} className={`csm-project ${p.isActive ? 'active' : ''}`}>

                      <button

                        className="csm-project-head"

                        onClick={() => toggleExpanded(`p-${p.id}`)}

                      >

                        <ChevronRight size={12} className={`csm-chevron ${open ? 'open' : ''}`}/>

                        <FileText size={13}/>

                        <span className="csm-project-name">{p.name}</span>

                        {p.versions > 0 && (

                          <span className="csm-versions" title={`${p.versions} version${p.versions === 1 ? '' : 's'} saved`}>

                            <Clock size={10}/>{p.versions}

                          </span>

                        )}

                      </button>

                      {open && (

                        <div className="csm-project-body">

                          <button className="csm-row" onClick={p.onOpen}>

                            <span className="csm-row-icon">📂</span>

                            <span>Open editor</span>

                          </button>

                          {p.sections.map(s => (

                            <button key={s.id} className="csm-row csm-row-section" onClick={s.onClick}>

                              <span className="csm-row-bullet"/>

                              <span className="csm-row-label">{s.name}</span>

                              {s.wc > 0 && <span className="csm-row-meta">{s.wc}</span>}

                            </button>

                          ))}

                          <div className="csm-row csm-row-foot">

                            <Clock size={11}/>

                            <span>{p.versions} version{p.versions === 1 ? '' : 's'} · auto-saved</span>

                          </div>

                          <div className="csm-row csm-row-foot">

                            <span style={{ color: 'var(--text-tertiary, #9CA3AF)' }}>{totalWords} words total</span>

                          </div>

                        </div>

                      )}

                    </div>

                  );

                });

              }



              // ---------- WORKSPACE: widgets grouped by category ----------

              if (canvasSubview === 'workspace') {

                const groups = widgetGroups

                  .map(g => ({

                    ...g,

                    items: g.items.filter(it => !q || it.label.toLowerCase().includes(q)),

                  }))

                  .filter(g => g.items.length > 0);

                if (groups.length === 0) {

                  return (

                    <div className="no-sessions">

                      {searchTerm ? 'No widgets match' : 'Workspace is empty — add widgets'}

                    </div>

                  );

                }

                return groups.map(g => {

                  const open = expanded[`g-${g.id}`] ?? true;

                  return (

                    <div key={g.id} className="csm-group">

                      <button className="csm-group-head" onClick={() => toggleExpanded(`g-${g.id}`)}>

                        <ChevronRight size={11} className={`csm-chevron ${open ? 'open' : ''}`}/>

                        <span className="csm-group-name">{g.label}</span>

                        <span className="csm-group-count">{g.items.length}</span>

                      </button>

                      {open && (

                        <div className="csm-group-body">

                          {g.items.map(it => (

                            <button key={it.id} className={`csm-row ${it.critic ? 'critic' : ''}`} onClick={it.onClick}>

                              <span className="csm-row-bullet"/>

                              <span className="csm-row-label">{it.label}</span>

                            </button>

                          ))}

                        </div>

                      )}

                    </div>

                  );

                });

              }



              // ---------- INSIGHTS: section list with confidence badges ----------

              if (canvasSubview === 'insights') {

                const sections = insightSections.filter(s => !q || s.name.toLowerCase().includes(q));

                if (sections.length === 0) {

                  return <div className="no-sessions">{searchTerm ? 'No sections match' : 'No insights yet'}</div>;

                }

                return (

                  <div className="csm-group">

                    <div className="csm-group-head" style={{ cursor: 'default' }}>

                      <span className="csm-group-name">Sections</span>

                      <span className="csm-group-count">{sections.length}</span>

                    </div>

                    <div className="csm-group-body">

                      {sections.map(s => {

                        const complete = s.taskCount > 0 && s.doneCount === s.taskCount;

                        return (

                          <button key={s.id} className={`csm-row ${complete ? 'csm-row-done' : ''}`} onClick={s.onClick}>

                            <span className="csm-row-bullet"/>

                            <span className="csm-row-label">{s.name}</span>

                            {s.taskCount > 0 && (

                              <span className="csm-row-meta">{s.doneCount}/{s.taskCount}</span>

                            )}

                          </button>

                        );

                      })}

                    </div>

                  </div>

                );

              }



              // ---------- Fallback: flat list (legacy) ----------

              const items = canvasItems.filter(it => !q || it.label.toLowerCase().includes(q));

              if (items.length === 0) {

                return <div className="no-sessions">{searchTerm ? 'No matches' : 'Nothing here yet'}</div>;

              }

              return (

                <div className="sessions-list">

                  {items.map((it) => (

                    <div key={it.id} className="session-item" onClick={it.onClick}>

                      <div className="session-content">

                        <div className="session-icon"><FileText size={16}/></div>

                        <div className="session-details">

                          <div className="session-title">{it.label}</div>

                          {it.sub && <div className="session-meta"><span>{it.sub}</span></div>}

                        </div>

                      </div>

                    </div>

                  ))}

                </div>

              );

            })()}

          </div>

        ) : (

        /* Chat Sessions */

        <div className="chat-sessions">

          {isLoading ? (

            <div className="loading-sessions">

              <div className="loading-spinner"></div>

              {!isCollapsed && <span>Loading chats...</span>}

            </div>

          ) : isCreatingNewChat ? (

            <div className="loading-sessions">

              <div className="loading-spinner"></div>

              {!isCollapsed && <span>Creating new chat...</span>}

            </div>

          ) : filteredSessions.length === 0 ? (

            <div className="no-sessions">

              {!isCollapsed && (searchTerm ? 'No chats found' : 'No chats yet')}

            </div>

          ) : (

            <div className="sessions-list">

              {filteredSessions.map((session) => (

                <div

                  key={session.id}

                  className={`session-item ${currentSessionId === session.id ? 'active' : ''} ${isCollapsed ? 'collapsed' : ''}`}

                  onClick={() => onSelectSession(session.id)}

                  title={isCollapsed ? session.title : ''}

                >

                  <div className="session-content">

                    <div className="session-icon">

                      <MessageSquare size={16} />

                    </div>

                    {!isCollapsed && (

                      <div className="session-details">

                        <div className="session-title">{session.title}</div>

                        <div className="session-meta">

                          <span className="session-date">{formatDate(session.updated_at)}</span>

                          <span className="session-messages">{session.message_count} messages</span>

                        </div>

                      </div>

                    )}

                  </div>

                  

                  {!isCollapsed && (

                    <button

                      className="session-menu-button"

                      onClick={(e) => handleDeleteSession(session.id, e)}

                    >

                      <Trash2 size={14} />

                    </button>

                  )}

                </div>

              ))}

            </div>

          )}

        </div>

        )}



        {/* Footer */}

        <div className={`sidebar-footer ${isCollapsed ? 'collapsed' : ''}`}>

          <a 

            href="https://neon.ai" 

            target="_blank" 

            rel="noopener noreferrer" 

            className="sidebar-neon-link"

            title="Neon.ai"

          >

            <img src="/neon-logo.png" alt="" className="sidebar-neon-logo" />

            {!isCollapsed && <span className="sidebar-neon-text">Neon.ai</span>}

          </a>

          {!isCollapsed && <CopyrightNotice variant="sidebar" />}

        </div>

      </div>

      

      {showAvatarPicker && (

        <UserAvatarPicker

          options={avatarOptions}

          currentId={userAvatarId}

          onSelect={(id) => { onAvatarChange?.(id); setShowAvatarPicker(false); }}

          onClose={() => setShowAvatarPicker(false)}

        />

      )}



      {isMobileOpen && (

        <div 

          className="mobile-sidebar-overlay visible" 

          onClick={() => onMobileToggle(false)}

        />

      )}

    </>
  );
};

export default Sidebar;