File size: 28,743 Bytes
61aec16
 
 
 
888b792
92dff23
1f5b714
35a414b
61aec16
 
 
 
 
d212ba6
61aec16
 
d212ba6
df1fcb2
1f5b714
f6d96e2
aca3d0b
da9637c
61aec16
 
 
 
df1fcb2
63e8029
d212ba6
61aec16
 
 
63e8029
 
 
 
 
 
 
 
 
 
df1fcb2
61aec16
 
aca3d0b
ffcd038
888b792
 
 
61aec16
 
92dff23
f6d96e2
61aec16
 
 
 
 
 
 
df1fcb2
aca3d0b
df1fcb2
63e8029
 
f6d96e2
d212ba6
 
 
ffcd038
1f5b714
9527547
888b792
 
 
35a414b
29c6e0c
888b792
 
 
a7c5777
888b792
 
 
 
a7c5777
888b792
 
 
 
 
 
 
 
 
 
 
 
 
ffcd038
 
 
 
 
 
 
 
 
 
 
 
 
 
61aec16
888b792
 
 
 
 
 
61aec16
df1fcb2
61aec16
df1fcb2
61aec16
 
 
df1fcb2
 
 
 
 
 
61aec16
df1fcb2
61aec16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df1fcb2
61aec16
 
888b792
 
 
 
 
 
 
 
 
 
 
61aec16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f96410
61aec16
 
 
 
 
 
 
 
 
 
7f96410
61aec16
 
 
 
 
7f96410
61aec16
 
 
 
 
 
 
 
888b792
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61aec16
 
 
df1fcb2
 
 
9527547
 
2ec0e37
9527547
2ec0e37
 
 
 
 
df5f0b0
2ec0e37
9527547
 
 
 
2ec0e37
 
9527547
 
bbe02b6
 
 
 
 
 
9527547
2ec0e37
9527547
 
 
df1fcb2
 
ffcd038
 
 
 
df1fcb2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61aec16
 
d212ba6
f6d96e2
ffcd038
 
 
 
f6d96e2
 
 
 
 
 
 
d212ba6
 
ffcd038
 
 
 
d212ba6
 
 
 
 
 
 
63e8029
 
ffcd038
 
 
 
f6d96e2
 
 
 
 
63e8029
f6d96e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63e8029
f6d96e2
63e8029
f6d96e2
 
 
 
63e8029
f6d96e2
63e8029
f6d96e2
 
 
 
63e8029
 
 
d212ba6
 
ffcd038
 
 
 
d212ba6
 
 
 
 
 
 
 
 
 
bfedc14
d212ba6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ffcd038
 
 
 
d212ba6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
888b792
 
 
61aec16
da9637c
 
d97497a
 
 
b9a4f82
d97497a
 
 
61aec16
f2ee9ec
31e4259
9b26f3a
f2ee9ec
9b26f3a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f2ee9ec
 
9b26f3a
 
 
 
31e4259
ffcd038
 
 
 
 
 
 
 
 
 
1f5b714
 
 
 
 
 
 
 
aca3d0b
 
 
 
 
35a414b
aca3d0b
35a414b
aca3d0b
92dff23
 
 
61aec16
 
 
 
 
d212ba6
61aec16
 
 
 
 
f6d96e2
 
 
 
 
ffcd038
f6d96e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d212ba6
 
 
 
 
ffcd038
d212ba6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61aec16
 
 
 
 
d212ba6
61aec16
 
 
 
 
d212ba6
61aec16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aca3d0b
9527547
 
 
 
 
 
 
61aec16
29c6e0c
b6e7627
aca3d0b
 
 
 
 
 
 
 
 
 
 
 
ffcd038
aca3d0b
888b792
 
 
 
a7c5777
 
35a414b
 
aca3d0b
 
 
 
 
 
 
 
 
 
 
 
61aec16
aca3d0b
61aec16
 
 
1f5b714
 
 
 
e1e6f89
9527547
 
 
 
1f5b714
 
 
61aec16
 
 
df1fcb2
d212ba6
df1fcb2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61aec16
da9637c
 
61aec16
 
 
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
/**
 * T080, T083-T084: Main application layout with two-pane design
 * Loads directory tree on mount and note + backlinks when path changes
 */
import { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { Plus, Settings as SettingsIcon, FolderPlus, MessageCircle } from 'lucide-react';
import { useFontSize } from '@/hooks/useFontSize';
import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from '@/components/ui/resizable';
import { Button } from '@/components/ui/button';
import { Separator } from '@/components/ui/separator';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { DirectoryTree } from '@/components/DirectoryTree';
import { DirectoryTreeSkeleton } from '@/components/DirectoryTreeSkeleton';
import { SearchBar } from '@/components/SearchBar';
import { NoteViewer } from '@/components/NoteViewer';
import { NoteViewerSkeleton } from '@/components/NoteViewerSkeleton';
import { NoteEditor } from '@/components/NoteEditor';
import { ChatPanel } from '@/components/ChatPanel';
import { useToast } from '@/hooks/useToast';
import { GraphView } from '@/components/GraphView';
import { GlowParticleEffect } from '@/components/GlowParticleEffect';
import {
  listNotes,
  getNote,
  getBacklinks,
  getIndexHealth,
  createNote,
  moveNote,
  type BacklinkResult,
  APIException,
} from '@/services/api';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import type { IndexHealth } from '@/types/search';
import type { Note, NoteSummary } from '@/types/note';
import { normalizeSlug } from '@/lib/wikilink';
import { Network } from 'lucide-react';
import { AUTH_TOKEN_CHANGED_EVENT, isDemoSession, login } from '@/services/auth';
import { synthesizeTts } from '@/services/tts';
import { markdownToPlainText } from '@/lib/markdownToText';
import { useAudioPlayer } from '@/hooks/useAudioPlayer';

export function MainApp() {
  const navigate = useNavigate();
  const toast = useToast();
  const [notes, setNotes] = useState<NoteSummary[]>([]);
  const [selectedPath, setSelectedPath] = useState<string | null>(null);
  const [currentNote, setCurrentNote] = useState<Note | null>(null);
  const [backlinks, setBacklinks] = useState<BacklinkResult[]>([]);
  const [isLoadingNotes, setIsLoadingNotes] = useState(true);
  const [isLoadingNote, setIsLoadingNote] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [isEditMode, setIsEditMode] = useState(false);
  const [isGraphView, setIsGraphView] = useState(false);
  const [indexHealth, setIndexHealth] = useState<IndexHealth | null>(null);
  const [isNewNoteDialogOpen, setIsNewNoteDialogOpen] = useState(false);
  const [newNoteName, setNewNoteName] = useState('');
  const [isCreatingNote, setIsCreatingNote] = useState(false);
  const [isNewFolderDialogOpen, setIsNewFolderDialogOpen] = useState(false);
  const [newFolderName, setNewFolderName] = useState('');
  const [isCreatingFolder, setIsCreatingFolder] = useState(false);
  const [isDemoMode, setIsDemoMode] = useState<boolean>(isDemoSession());
  const [isChatOpen, setIsChatOpen] = useState(false);
  const [graphRefreshTrigger, setGraphRefreshTrigger] = useState(0);
  const [isSynthesizingTts, setIsSynthesizingTts] = useState(false);
  const ttsUrlRef = useRef<string | null>(null);
  const ttsAbortRef = useRef<AbortController | null>(null);
  // T007: Initialize font size state management
  const { fontSize, setFontSize, isFontReady } = useFontSize();
  const {
    status: ttsPlayerStatus,
    error: ttsPlayerError,
    volume: ttsVolume,
    play: playAudio,
    pause: pauseAudio,
    resume: resumeAudio,
    stop: stopAudio,
    setVolume: setTtsVolume,
  } = useAudioPlayer();
  const stopTts = () => {
    if (ttsAbortRef.current) {
      ttsAbortRef.current.abort();
      ttsAbortRef.current = null;
    }
    stopAudio();
    if (ttsUrlRef.current) {
      URL.revokeObjectURL(ttsUrlRef.current);
      ttsUrlRef.current = null;
    }
    setIsSynthesizingTts(false);
  };

  useEffect(() => {
    const handleAuthChange = () => {
      const demo = isDemoSession();
      setIsDemoMode(demo);
      if (demo) {
        setIsEditMode(false);
      }
    };
    window.addEventListener(AUTH_TOKEN_CHANGED_EVENT, handleAuthChange);
    return () => {
      window.removeEventListener(AUTH_TOKEN_CHANGED_EVENT, handleAuthChange);
    };
  }, []);

  useEffect(() => {
    if (ttsPlayerError) {
      toast.error(ttsPlayerError);
    }
  }, [ttsPlayerError, toast]);

  // T083: Load directory tree on mount
  // T119: Load index health
  useEffect(() => {
    const loadData = async () => {
      setIsLoadingNotes(true);
      setError(null);
      try {
        // Load notes and index health in parallel
        const [notesList, health] = await Promise.all([
          listNotes(),
          getIndexHealth().catch(() => null), // Don't fail if health unavailable
        ]);
        
        setNotes(notesList);
        setIndexHealth(health);
        
        // Auto-select first note if available
        if (notesList.length > 0 && !selectedPath) {
          setSelectedPath(notesList[0].note_path);
        }
      } catch (err) {
        if (err instanceof APIException) {
          setError(err.error);
        } else {
          setError('Failed to load notes');
        }
        console.error('Error loading notes:', err);
      } finally {
        setIsLoadingNotes(false);
      }
    };

    loadData();
  }, []);

  useEffect(() => {
    // Stop TTS when switching notes
    stopTts();
  }, [selectedPath]);

  useEffect(() => {
    return () => {
      stopTts();
    };
  }, []);

  // T084: Load note and backlinks when path changes
  useEffect(() => {
    if (!selectedPath) {
      setCurrentNote(null);
      setBacklinks([]);
      return;
    }

    const loadNote = async () => {
      setIsLoadingNote(true);
      setError(null);
      try {
        const [note, noteBacklinks] = await Promise.all([
          getNote(selectedPath),
          getBacklinks(selectedPath),
        ]);
        setCurrentNote(note);
        setBacklinks(noteBacklinks);
      } catch (err) {
        if (err instanceof APIException) {
          setError(err.error);
        } else {
          setError('Failed to load note');
        }
        console.error('Error loading note:', err);
        setCurrentNote(null);
        setBacklinks([]);
      } finally {
        setIsLoadingNote(false);
      }
    };

    loadNote();
  }, [selectedPath]);

  // Handle wikilink clicks
  const handleWikilinkClick = async (linkText: string) => {
    const slug = normalizeSlug(linkText);
    console.log(`[Wikilink] Clicked: "${linkText}", Slug: "${slug}"`);
    
    // Try to find exact match first
    let targetNote = notes.find(
      (note) => normalizeSlug(note.title) === slug
    );

    // If not found, try path-based matching
    if (!targetNote) {
      targetNote = notes.find((note) => {
        const pathSlug = normalizeSlug(note.note_path.replace(/\.md$/, ''));
        // console.log(`Checking path: ${note.note_path}, Slug: ${pathSlug}`);
        return pathSlug.endsWith(slug);
      });
    }

    if (targetNote) {
      console.log(`[Wikilink] Found target: ${targetNote.note_path}`);
      setSelectedPath(targetNote.note_path);
    } else {
      // TODO: Show "Create note" dialog
      console.log('Note not found for wikilink:', linkText);
      setError(`Note not found: ${linkText}`);
    }
  };

  const handleTtsToggle = async () => {
    if (!currentNote || isSynthesizingTts) {
      return;
    }

    if (ttsPlayerStatus === 'playing') {
      pauseAudio();
      return;
    }

    if (ttsPlayerStatus === 'paused') {
      resumeAudio();
      return;
    }

    const plainText = markdownToPlainText(currentNote.body);
    if (!plainText) {
      toast.error('No readable content in this note.');
      return;
    }

    if (ttsAbortRef.current) {
      ttsAbortRef.current.abort();
    }
    const controller = new AbortController();
    ttsAbortRef.current = controller;
    setIsSynthesizingTts(true);
    try {
      const blob = await synthesizeTts(plainText, { signal: controller.signal });
      if (ttsUrlRef.current) {
        URL.revokeObjectURL(ttsUrlRef.current);
      }
      const url = URL.createObjectURL(blob);
      ttsUrlRef.current = url;
      playAudio(url);
    } catch (err) {
      if (err instanceof DOMException && err.name === 'AbortError') {
        return;
      }
      const message = err instanceof Error ? err.message : 'Failed to generate speech.';
      toast.error(message);
    } finally {
      ttsAbortRef.current = null;
      setIsSynthesizingTts(false);
    }
  };

  const handleTtsStop = () => {
    stopTts();
  };

  const handleSelectNote = (path: string) => {
    setSelectedPath(path);
    setError(null);
    setIsEditMode(false); // Exit edit mode when switching notes
  };

  // Refresh all views when notes are changed
  const refreshAll = async () => {
    console.log('[MainApp] refreshAll called');
    try {
      // Note: Backend automatically updates index when notes are created
      // We just need to fetch the fresh data

      // Small delay to ensure backend indexing completes
      await new Promise(resolve => setTimeout(resolve, 500));

      // Fetch fresh data
      const [notesList, health] = await Promise.all([
        listNotes(),
        getIndexHealth().catch(() => null)
      ]);

      console.log('[MainApp] Fetched', notesList.length, 'notes');
      setNotes(notesList);
      setIndexHealth(health);
      setGraphRefreshTrigger(prev => {
        const newValue = prev + 1;
        console.log('[MainApp] Graph trigger:', prev, '→', newValue);
        return newValue;
      });
      console.log('[MainApp] State updated');
    } catch (err) {
      console.error('[MainApp] Error refreshing data:', err);
    }
  };

  // T093: Handle edit button click
  const handleEdit = () => {
    if (isDemoMode) {
      toast.error('Demo mode is read-only. Sign in with Hugging Face to edit notes.');
      return;
    }
    setIsEditMode(true);
  };

  // Handle note save from editor
  const handleNoteSave = (updatedNote: Note) => {
    setCurrentNote(updatedNote);
    setIsEditMode(false);
    setError(null);
    // Reload notes list to update modified timestamp
    listNotes().then(setNotes).catch(console.error);
  };

  // Handle editor cancel
  const handleEditCancel = () => {
    setIsEditMode(false);
  };

  // Handle note dialog open change
  const handleDialogOpenChange = (open: boolean) => {
    if (open && isDemoMode) {
      toast.error('Demo mode is read-only. Sign in with Hugging Face to create notes.');
      return;
    }
    setIsNewNoteDialogOpen(open);
    if (!open) {
      // Clear input when dialog closes
      setNewNoteName('');
    }
  };

  // Handle folder dialog open change
  const handleFolderDialogOpenChange = (open: boolean) => {
    if (open && isDemoMode) {
      toast.error('Demo mode is read-only. Sign in with Hugging Face to create folders.');
      return;
    }
    setIsNewFolderDialogOpen(open);
    if (!open) {
      // Clear input when dialog closes
      setNewFolderName('');
    }
  };

  // Handle create new note
  const handleCreateNote = async () => {
    if (isDemoMode) {
      toast.error('Demo mode is read-only. Sign in to create notes.');
      return;
    }
    if (!newNoteName.trim() || isCreatingNote) return;

    setIsCreatingNote(true);
    setError(null);

    try {
      const baseName = newNoteName.replace(/\.md$/, '');
      let notePath = newNoteName.endsWith('.md') ? newNoteName : `${newNoteName}.md`;
      let attempt = 1;
      const maxAttempts = 100;

      // Retry with number suffix if note already exists
      while (attempt <= maxAttempts) {
        try {
          const note = await createNote({
            note_path: notePath,
            title: baseName,
            body: `# ${baseName}\n\nStart writing your note here...`,
          });

          // Refresh notes list
          const notesList = await listNotes();
          setNotes(notesList);

          // Select the new note
          setSelectedPath(note.note_path);
          setIsEditMode(true);
          const displayName = notePath.replace(/\.md$/, '');
          toast.success(`Note "${displayName}" created successfully`);
          break;
        } catch (err) {
          if (err instanceof APIException && err.status === 409) {
            // Note already exists, try with number suffix
            attempt++;
            if (attempt <= maxAttempts) {
              notePath = `${baseName} ${attempt}.md`;
              continue;
            } else {
              throw err;
            }
          } else {
            throw err;
          }
        }
      }
    } catch (err) {
      let errorMessage = 'Failed to create note';
      if (err instanceof APIException) {
        // Use the message field which contains the actual error description
        errorMessage = err.message || err.error;
      } else if (err instanceof Error) {
        errorMessage = err.message;
      }
      toast.error(errorMessage);
      console.error('Error creating note:', err);
    } finally {
      setIsCreatingNote(false);
      // Always close dialog, regardless of success or failure
      handleDialogOpenChange(false);
    }
  };

  // Handle create new folder
  const handleCreateFolder = async () => {
    if (isDemoMode) {
      toast.error('Demo mode is read-only. Sign in to create folders.');
      return;
    }
    if (!newFolderName.trim() || isCreatingFolder) return;

    setIsCreatingFolder(true);
    setError(null);

    try {
      // Create a placeholder note in the folder
      const folderPath = newFolderName.replace(/\/$/, ''); // Remove trailing slash if present
      const placeholderPath = `${folderPath}/.placeholder.md`;

      await createNote({
        note_path: placeholderPath,
        title: 'Folder',
        body: `# ${folderPath}\n\nThis folder was created.`,
      });

      // Refresh notes list
      const notesList = await listNotes();
      setNotes(notesList);

      toast.success(`Folder "${folderPath}" created successfully`);
    } catch (err) {
      let errorMessage = 'Failed to create folder';
      if (err instanceof APIException) {
        errorMessage = err.message || err.error;
      } else if (err instanceof Error) {
        errorMessage = err.message;
      }
      toast.error(errorMessage);
      console.error('Error creating folder:', err);
    } finally {
      setIsCreatingFolder(false);
      // Always close dialog, regardless of success or failure
      handleFolderDialogOpenChange(false);
    }
  };

  // Handle dragging file to folder
  const handleMoveNoteToFolder = async (oldPath: string, targetFolderPath: string) => {
    if (isDemoMode) {
      toast.error('Demo mode is read-only. Sign in to move notes.');
      return;
    }
    try {
      // Get the filename from the old path
      const fileName = oldPath.split('/').pop();
      if (!fileName) {
        toast.error('Invalid file path');
        return;
      }

      // Construct new path: targetFolder/fileName
      const newPath = targetFolderPath ? `${targetFolderPath}/${fileName}` : fileName;

      // Don't move if source and destination are the same
      if (newPath === oldPath) {
        return;
      }

      await moveNote(oldPath, newPath);

      // Refresh notes list
      const notesList = await listNotes();
      setNotes(notesList);

      // If moving currently selected note, update selection
      if (selectedPath === oldPath) {
        setSelectedPath(newPath);
      }

      toast.success(`Note moved successfully`);
    } catch (err) {
      let errorMessage = 'Failed to move note';
      if (err instanceof APIException) {
        errorMessage = err.message || err.error;
      } else if (err instanceof Error) {
        errorMessage = err.message;
      }
      toast.error(errorMessage);
      console.error('Error moving note:', err);
    }
  };

  const ttsStatus = isSynthesizingTts ? 'loading' : ttsPlayerStatus;
  const ttsDisabledReason = undefined;

  return (
    <GlowParticleEffect config="vibrant" triggerSelector="button">
      <div className="h-screen flex flex-col">
      {/* Demo warning banner */}
      <Alert variant="destructive" className="rounded-none border-x-0 border-t-0">
        <AlertDescription className="text-center">
          DEMO ONLY - ALL DATA IS TEMPORARY AND MAY BE DELETED AT ANY TIME
        </AlertDescription>
      </Alert>
      
      {/* Top bar */}
      <div className="border-b border-border p-2 animate-fade-in">
        <div className="relative flex items-center justify-center">
          <h1
            className="text-2xl tracking-[0.15em] uppercase select-none"
            style={{
              fontFamily: '"Press Start 2P", monospace',
              fontWeight: 400,
              color: "#3b82f6",
              textShadow: `
                0px 0px 1px #000000,
                1px 1px 0 #111827,
                2px 2px 0 #020617,
                3px 3px 0 #020617,
                4px 4px 0 #020617,
                5px 5px 0 #020617,
                0px 0px 4px rgba(15,23,42,0.9),
                0px 0px 10px rgba(59,130,246,0.7)
              `,
              textRendering: "geometricPrecision",
              WebkitFontSmoothing: "none",
              transform: "perspective(700px) rotateX(18deg)",
              transformOrigin: "bottom center",
            }}
          >
            Vault.MCP
          </h1>
          <div className="absolute right-0 flex gap-2">
            {isDemoMode && (
              <Button
                variant="default"
                size="sm"
                onClick={() => login()}
                title="Sign in with Hugging Face"
              >
                Sign in
              </Button>
            )}
            <Button
              variant={isChatOpen ? "secondary" : "ghost"}
              size="sm"
              onClick={() => setIsChatOpen(!isChatOpen)}
              title={isChatOpen ? "Close Chat" : "Open AI Planning Agent"}
            >
              <MessageCircle className="h-4 w-4" />
            </Button>
            <Button
              variant={isGraphView ? "secondary" : "ghost"}
              size="sm"
              onClick={() => setIsGraphView(!isGraphView)}
              title={isGraphView ? "Switch to Note View" : "Switch to Graph View"}
              className="transition-all duration-250 ease-out"
            >
              <Network className="h-4 w-4 transition-transform duration-250" />
            </Button>
            <Button variant="ghost" size="sm" onClick={() => navigate('/settings')}>
              <SettingsIcon className="h-4 w-4" />
            </Button>
          </div>
        </div>
      </div>

      {/* Main content */}
      <div className="flex-1 overflow-hidden animate-fade-in" style={{ animationDelay: '0.1s' }}>
        <ResizablePanelGroup direction="horizontal">
          {/* Left sidebar */}
          <ResizablePanel defaultSize={25} minSize={15} maxSize={40}>
            <div className="h-full flex flex-col">
              <div className="p-4 space-y-4">
                <Dialog
                  open={isNewNoteDialogOpen}
                  onOpenChange={handleDialogOpenChange}
                >
                  <DialogTrigger asChild>
                    <Button variant="outline" size="sm" className="w-full" disabled={isDemoMode}>
                      <Plus className="h-4 w-4 mr-1" />
                      New Note
                    </Button>
                  </DialogTrigger>
                  <DialogContent>
                    <DialogHeader>
                      <DialogTitle>Create New Note</DialogTitle>
                      <DialogDescription>
                        Enter a name for your new note. The .md extension will be added automatically if not provided.
                      </DialogDescription>
                    </DialogHeader>
                    <div className="grid gap-4 py-4">
                      <div className="grid gap-2">
                        <label htmlFor="note-name" className="text-sm font-medium">Note Name</label>
                        <Input
                          id="note-name"
                          placeholder="my-note"
                          value={newNoteName}
                          onChange={(e) => setNewNoteName(e.target.value)}
                          onKeyDown={(e) => {
                            if (e.key === 'Enter') {
                              handleCreateNote();
                            }
                          }}
                        />
                      </div>
                    </div>
                    <DialogFooter>
                      <Button
                        variant="outline"
                        onClick={() => setIsNewNoteDialogOpen(false)}
                        disabled={isCreatingNote}
                      >
                        Cancel
                      </Button>
                      <Button
                        onClick={handleCreateNote}
                        disabled={!newNoteName.trim() || isCreatingNote}
                      >
                        {isCreatingNote ? 'Creating...' : 'Create Note'}
                      </Button>
                    </DialogFooter>
                  </DialogContent>
                </Dialog>
                <Dialog
                  open={isNewFolderDialogOpen}
                  onOpenChange={handleFolderDialogOpenChange}
                >
                  <DialogTrigger asChild>
                    <Button variant="outline" size="sm" className="w-full" disabled={isDemoMode}>
                      <FolderPlus className="h-4 w-4 mr-1" />
                      New Folder
                    </Button>
                  </DialogTrigger>
                  <DialogContent>
                    <DialogHeader>
                      <DialogTitle>Create New Folder</DialogTitle>
                      <DialogDescription>
                        Enter a name for your new folder. You can use forward slashes for nested folders (e.g., "Projects/Work").
                      </DialogDescription>
                    </DialogHeader>
                    <div className="grid gap-4 py-4">
                      <div className="grid gap-2">
                        <label htmlFor="folder-name" className="text-sm font-medium">Folder Name</label>
                        <Input
                          id="folder-name"
                          placeholder="my-folder"
                          value={newFolderName}
                          onChange={(e) => setNewFolderName(e.target.value)}
                          onKeyDown={(e) => {
                            if (e.key === 'Enter') {
                              handleCreateFolder();
                            }
                          }}
                        />
                      </div>
                    </div>
                    <DialogFooter>
                      <Button
                        variant="outline"
                        onClick={() => setIsNewFolderDialogOpen(false)}
                        disabled={isCreatingFolder}
                      >
                        Cancel
                      </Button>
                      <Button
                        onClick={handleCreateFolder}
                        disabled={!newFolderName.trim() || isCreatingFolder}
                      >
                        {isCreatingFolder ? 'Creating...' : 'Create Folder'}
                      </Button>
                    </DialogFooter>
                  </DialogContent>
                </Dialog>
                <SearchBar onSelectNote={handleSelectNote} />
                <Separator />
              </div>
              <div className="flex-1 overflow-hidden">
                {isLoadingNotes ? (
                  <DirectoryTreeSkeleton />
                ) : (
                  <DirectoryTree
                    notes={notes}
                    selectedPath={selectedPath || undefined}
                    onSelectNote={handleSelectNote}
                    onMoveNote={handleMoveNoteToFolder}
                  />
                )}
              </div>
            </div>
          </ResizablePanel>

          <ResizableHandle withHandle />

          {/* Main content pane */}
          <ResizablePanel defaultSize={75}>
            <div className="h-full bg-background">
              {error && (
                <div className="p-4">
                  <Alert variant="destructive">
                    <AlertDescription>{error}</AlertDescription>
                  </Alert>
                </div>
              )}

              {isGraphView ? (
                <GraphView
                  onSelectNote={(path) => {
                    handleSelectNote(path);
                    setIsGraphView(false);
                  }}
                  refreshTrigger={graphRefreshTrigger}
                />
              ) : (
                isLoadingNote || !isFontReady ? (
                  <NoteViewerSkeleton />
                ) : currentNote ? (
                  isEditMode ? (
                    <NoteEditor
                      note={currentNote}
                      onSave={handleNoteSave}
                      onCancel={handleEditCancel}
                      onWikilinkClick={handleWikilinkClick}
                    />
                  ) : (
                    <NoteViewer
                      note={currentNote}
                      backlinks={backlinks}
                      onEdit={isDemoMode ? undefined : handleEdit}
                      onWikilinkClick={handleWikilinkClick}
                      ttsStatus={ttsStatus}
                      onTtsToggle={handleTtsToggle}
                      onTtsStop={handleTtsStop}
                      ttsDisabledReason={ttsDisabledReason}
                      ttsVolume={ttsVolume}
                      onTtsVolumeChange={setTtsVolume}
                      fontSize={fontSize}
                      onFontSizeChange={setFontSize}
                    />
                  )
                ) : (
                  <div className="flex items-center justify-center h-full">
                    <div className="text-center text-muted-foreground">
                      <p className="text-lg mb-2">Select a note to view</p>
                      <p className="text-sm">
                        {notes.length === 0
                          ? 'No notes available. Create your first note to get started.'
                          : 'Choose a note from the sidebar'}
                      </p>
                    </div>
                  </div>
                )
              )}
            </div>
          </ResizablePanel>

          {isChatOpen && (
            <>
              <ResizableHandle withHandle />
              <ResizablePanel defaultSize={25} minSize={20} maxSize={40} className="animate-slide-in">
                <ChatPanel
                  onNavigateToNote={handleSelectNote}
                  onNotesChanged={refreshAll}
                />
              </ResizablePanel>
            </>
          )}
        </ResizablePanelGroup>
      </div>

      {/* Footer with Index Health */}
      <div className="border-t border-border px-4 py-2 text-xs text-muted-foreground animate-fade-in" style={{ animationDelay: '0.2s' }}>
        <div className="flex items-center justify-between">
          <div>
            {indexHealth ? (
              <>
                <span className="font-medium">{indexHealth.note_count}</span> note{indexHealth.note_count !== 1 ? 's' : ''} indexed
              </>
            ) : (
              <>
                <span className="font-medium">{notes.length}</span> note{notes.length !== 1 ? 's' : ''} indexed
              </>
            )}
          </div>
          {indexHealth && indexHealth.last_incremental_update && (
            <div className="flex items-center gap-2">
              <span>Last updated:</span>
              <span className="font-medium">
                {new Date(indexHealth.last_incremental_update).toLocaleString('en-US', {
                  month: 'short',
                  day: 'numeric',
                  hour: '2-digit',
                  minute: '2-digit',
                })}
              </span>
            </div>
          )}
        </div>
      </div>
      </div>
    </GlowParticleEffect>
  );
}