Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

34.7 KB
Raw Blame
import { useState, useEffect, useCallback, useRef } from 'react';
import * as api from '../../../services/api';
import {
  BookOpen,
  FolderOpen,
  Search,
  Plus,
  ChevronRight,
  ChevronDown,
  ArrowLeft,
  Tag,
  Link2,
  RefreshCw,
  FileText,
  X,
  Settings
} from 'lucide-react';
import BrailleSpinner from '../../BrailleSpinner';
import toast from '../../ui/Toast';
import FolderPicker from '../../FolderPicker';
import { formatCount } from '../../../utils/formatters';
import { useConfirmDelete } from '../../../hooks/useConfirmDelete';
import { useNoteSave } from '../../../hooks/useNoteSave.js';
import useUrlParams from '../../../hooks/useUrlParams';
import { clickableProps, onActivateKeyDown } from '../../../lib/a11yKeyboard.js';
import OfflineNotesNotice from '../../OfflineNotesNotice.jsx';
import NoteDetailPane from '../../notes/NoteDetailPane.jsx';
import useVaultNote from '../../../hooks/useVaultNote.js';
import MarkdownOutput from '../../cos/MarkdownOutput.jsx';

function UnavailableState({ title, message, onRetry }) {
  return (
    <div role="alert" className="rounded-lg border border-port-error/40 bg-port-error/10 p-4 text-sm text-gray-300">
      <p className="font-medium text-port-error">{title}</p>
      <p className="mt-1 text-gray-400">{message}</p>
      <button
        type="button"
        onClick={onRetry}
        className="mt-3 min-h-[44px] rounded bg-port-card px-3 text-port-accent hover:text-white"
      >
        Retry
      </button>
    </div>
  );
}

export default function NotesTab() {
  const [searchParams, updateParams] = useUrlParams();
  const selectedVaultId = searchParams.get('vault') || null;
  const folderFilter = searchParams.get('folder') || '';
  const searchQuery = searchParams.get('q') || '';
  const selectedNotePath = searchParams.get('note') || null;

  // Vault state
  const [vaults, setVaults] = useState([]);
  const [detectedVaults, setDetectedVaults] = useState([]);
  const [showVaultSetup, setShowVaultSetup] = useState(false);
  const [addingVault, setAddingVault] = useState(false);
  const [customPath, setCustomPath] = useState('');
  const [vaultError, setVaultError] = useState(false);
  const [detectError, setDetectError] = useState(false);

  // Notes state
  const [notes, setNotes] = useState([]);
  const [notesKey, setNotesKey] = useState(null);
  const [totalNotes, setTotalNotes] = useState(0);
  // Notes the server skipped because iCloud hasn't downloaded them — surfaced so
  // an incomplete list isn't presented as the whole vault.
  const [skippedNotes, setSkippedNotes] = useState(0);
  const [loading, setLoading] = useState(true);
  const [scanning, setScanning] = useState(false);
  const [scanError, setScanError] = useState(false);

  // Note viewer/editor state
  const [noteContent, setNoteContent] = useState('');
  const [editing, setEditing] = useState(false);
  const {
    note: selectedNote, setNote: setSelectedNote, loading: loadingNote,
    error: noteError, retry: retryNote, clear: clearNote, sequenceRef: selectSeqRef,
  } = useVaultNote(selectedVaultId, selectedNotePath, {
    onReset: () => {
      setNoteContent('');
      setEditing(false);
      dismissForce();
      cancelDelete();
    },
    onLoad: note => setNoteContent(note.content),
  });

  // Search state
  const [searchInput, setSearchInput] = useState(searchQuery);
  const [searchResults, setSearchResults] = useState(null);
  const [searching, setSearching] = useState(false);
  const [searchError, setSearchError] = useState(false);

  // Filter state
  const [, setFolders] = useState([]);
  const [expandedFolders, setExpandedFolders] = useState(new Set());
  const [tags, setTags] = useState([]);
  const [showTags, setShowTags] = useState(false);

  // Create note state
  const [showCreateForm, setShowCreateForm] = useState(false);
  const [newNotePath, setNewNotePath] = useState('');
  const [creating, setCreating] = useState(false);

  // Confirm delete
  const { isConfirming: isConfirmingDelete, requestDelete, cancelDelete } = useConfirmDelete();

  // Owns the write plus the iCloud force-save escape hatch (#3717).
  const { saving, save, forceOffered, dismissForce, bufferChangedSince } = useNoteSave({
    vaultId: selectedVaultId,
    notePath: selectedNote?.path || null,
    content: noteContent
  });

  const searchRef = useRef(null);

  // Invalidate work at the interaction boundary, including A → B → A switches.
  const vaultScopeRef = useRef(0);
  const scopedVaultRef = useRef(selectedVaultId);
  const scanSeqRef = useRef(0);
  const searchSeqRef = useRef(0);
  const mountedRef = useRef(false);
  const isCurrentScope = scope => mountedRef.current && vaultScopeRef.current === scope;

  const clearSelection = () => {
    clearNote();
    dismissForce();
    cancelDelete();
  };

  const resetVaultScope = vaultId => {
    scopedVaultRef.current = vaultId;
    vaultScopeRef.current += 1;
    scanSeqRef.current += 1;
    searchSeqRef.current += 1;
    clearSelection();
    setNotes([]);
    setNotesKey(null);
    setTotalNotes(0);
    setSkippedNotes(0);
    setFolders([]);
    setTags([]);
    setShowTags(false);
    setExpandedFolders(new Set());
    setSearchInput('');
    setSearchResults(null);
    setSearchError(false);
    setShowCreateForm(false);
    setNewNotePath('');
    setCreating(false);
    setScanning(false);
    setScanError(false);
  };

  const selectVault = (vaultId, options = {}) => {
    resetVaultScope(vaultId);
    updateParams({ vault: vaultId, folder: null, q: null, note: null }, options);
  };

  // History navigation changes the URL without going through the selector.
  // Invalidate the old vault before starting any reads for the restored URL.
  useEffect(() => {
    if (scopedVaultRef.current !== selectedVaultId) resetVaultScope(selectedVaultId);
  }, [selectedVaultId]);

  // Load vaults on mount
  useEffect(() => {
    mountedRef.current = true;
    loadVaults();
    return () => {
      mountedRef.current = false;
      vaultScopeRef.current += 1;
      selectSeqRef.current += 1;
      scanSeqRef.current += 1;
      searchSeqRef.current += 1;
    };
  }, []);

  // Load notes when vault changes
  useEffect(() => {
    if (selectedVaultId) {
      loadNotes();
      loadFolders();
    }
  }, [selectedVaultId, folderFilter]);

  const loadVaults = async (preferredVaultId) => {
    const scope = vaultScopeRef.current;
    setVaultError(false);
    const data = await api.getNotesVaults({ silent: true }).catch(() => null);
    if (!isCurrentScope(scope)) return;
    if (!data) {
      setVaultError(true);
      setLoading(false);
      return;
    }
    setVaults(data);
    setVaultError(false);
    if (data.length > 0) {
      const requestedVaultId = preferredVaultId || selectedVaultId;
      const nextVaultId = data.some(vault => vault.id === requestedVaultId)
        ? requestedVaultId
        : data[0].id;
      if (nextVaultId !== selectedVaultId) {
        selectVault(nextVaultId, { replace: true });
      }
    }
    if (data.length === 0) {
      setShowVaultSetup(true);
      detectAvailableVaults();
    }
    setLoading(false);
  };

  const detectAvailableVaults = async () => {
    const scope = vaultScopeRef.current;
    setDetectError(false);
    const detected = await api.detectNotesVaults({ silent: true }).catch(() => null);
    if (!isCurrentScope(scope)) return;
    if (detected) setDetectedVaults(detected);
    else setDetectError(true);
  };

  const loadNotes = async () => {
    if (!selectedVaultId) return;
    const scope = vaultScopeRef.current;
    const sequence = ++scanSeqRef.current;
    const requestKey = `${selectedVaultId}\u0000${folderFilter}`;
    setScanning(true);
    setScanError(false);
    const data = await api.scanNotesVault(selectedVaultId, { folder: folderFilter, limit: 500, silent: true }).catch(() => null);
    if (!isCurrentScope(scope) || sequence !== scanSeqRef.current) return;
    if (data) {
      setNotes(data.notes);
      setNotesKey(requestKey);
      setTotalNotes(data.total);
      setSkippedNotes(data.skippedUnavailable || 0);
    } else setScanError(true);
    setScanning(false);
  };

  const loadFolders = async () => {
    if (!selectedVaultId) return;
    const scope = vaultScopeRef.current;
    const data = await api.getNotesVaultFolders(selectedVaultId, { silent: true }).catch(() => null);
    if (isCurrentScope(scope) && data?.folders) setFolders(data.folders);
  };

  const loadTags = async () => {
    if (!selectedVaultId) return;
    const scope = vaultScopeRef.current;
    const data = await api.getNotesVaultTags(selectedVaultId).catch(() => null);
    if (isCurrentScope(scope) && data?.tags) setTags(data.tags);
  };

  const loadSearch = useCallback(async (query = searchQuery) => {
    if (!query.trim() || !selectedVaultId) return;
    const scope = vaultScopeRef.current;
    const sequence = ++searchSeqRef.current;
    setSearching(true);
    setSearchError(false);
    const data = await api.searchNotes(selectedVaultId, query.trim(), undefined, { silent: true }).catch(() => null);
    if (!mountedRef.current || scope !== vaultScopeRef.current || sequence !== searchSeqRef.current) return;
    if (data) setSearchResults(data);
    else setSearchError(true);
    setSearching(false);
  }, [searchQuery, selectedVaultId]);

  useEffect(() => {
    setSearchInput(searchQuery);
    if (!searchQuery || !selectedVaultId) {
      searchSeqRef.current += 1;
      setSearchResults(null);
      setSearchError(false);
      setSearching(false);
      return;
    }
    setSearchResults(null);
    loadSearch(searchQuery);
  }, [selectedVaultId, searchQuery, loadSearch]);

  const handleAddVault = async (name, path) => {
    const scope = vaultScopeRef.current;
    setAddingVault(true);
    const result = await api.addNotesVault({ name, path }, { silent: true }).catch((error) => {
      toast.error(error?.message || 'Failed to add vault');
      return null;
    });
    if (!isCurrentScope(scope)) return;
    setAddingVault(false);
    if (result) {
      toast.success(`Added vault: ${result.name}`);
      setShowVaultSetup(false);
      selectVault(result.id);
      await loadVaults(result.id);
    }
  };

  const handleSelectNote = (notePath) => {
    clearSelection();
    retryNote();
    updateParams({ note: notePath });
  };

  const closeNote = () => {
    clearSelection();
    updateParams({ note: null });
  };

  // `force` is ONLY ever passed by <ForceSaveNoteRow>'s confirm (#3717) — never
  // by the Save button or ⌘S.
  const handleSaveNote = async (options) => {
    const scope = vaultScopeRef.current;
    const sequence = selectSeqRef.current;
    const submitted = noteContent;
    const data = await save(options);
    if (!data || !isCurrentScope(scope) || sequence !== selectSeqRef.current) return;
    setSelectedNote(data);
    // Text typed while the write was in flight was never submitted: keep it
    // visible and unsaved instead of closing the editor over it.
    if (!bufferChangedSince(submitted)) setEditing(false);
    toast.success('Note saved');
    loadNotes(); // Refresh metadata
  };

  const handleCreateNote = async () => {
    if (!newNotePath.trim()) return;
    const scope = vaultScopeRef.current;
    const sequence = selectSeqRef.current;
    setCreating(true);
    const data = await api.createNote(selectedVaultId, newNotePath.trim(), '', { silent: true }).catch((error) => {
      toast.error(error?.message || 'Failed to create note');
      return null;
    });
    if (!isCurrentScope(scope)) return;
    setCreating(false);
    if (data) {
      toast.success(`Created: ${data.name}`);
      setShowCreateForm(false);
      setNewNotePath('');
      loadNotes();
      if (sequence === selectSeqRef.current) handleSelectNote(data.path);
    }
  };

  const handleDeleteNote = async (notePath) => {
    const scope = vaultScopeRef.current;
    const sequence = selectSeqRef.current;
    const deleted = await api.deleteNote(selectedVaultId, notePath, { silent: true })
      .then(() => true)
      .catch((error) => {
        toast.error(error?.message || 'Failed to delete note');
        return false;
      });
    if (!deleted || !isCurrentScope(scope)) return;
    toast.success('Note deleted');
    cancelDelete();
    setNotes(prev => prev.filter(n => n.path !== notePath));
    if (sequence === selectSeqRef.current && selectedNotePath === notePath) {
      clearSelection();
      updateParams({ note: null });
    }
  };

  const handleSearch = useCallback((query = searchInput) => {
    updateParams({ q: query.trim() || null });
  }, [searchInput, updateParams]);

  const clearSearch = () => {
    searchSeqRef.current += 1;
    setSearchInput('');
    setSearchResults(null);
    setSearchError(false);
    updateParams({ q: null });
  };

  const toggleFolder = (folder) => {
    setExpandedFolders(prev => {
      const next = new Set(prev);
      if (next.has(folder)) next.delete(folder);
      else next.add(folder);
      return next;
    });
  };

  // Vault setup / empty state
  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <BrailleSpinner text="Loading" />
      </div>
    );
  }

  if (vaultError && vaults.length === 0) {
    return (
      <div className="h-full overflow-y-auto p-3 sm:p-4">
        <UnavailableState
          title="Notes vaults are unavailable"
          message="The vault list could not be read, so PortOS cannot tell whether this install has any notes."
          onRetry={() => loadVaults()}
        />
      </div>
    );
  }

  if (showVaultSetup || vaults.length === 0) {
    // Notes is a full-bleed tab (Brain wraps it in overflow-hidden with no
    // padding), so this branch must own its scroll + padding — otherwise the
    // vault manager clips below the fold with no scrollbar (#1177).
    return (
      <div className="h-full overflow-y-auto p-3 sm:p-4">
        <VaultSetup
          detectedVaults={detectedVaults}
          vaults={vaults}
          customPath={customPath}
          setCustomPath={setCustomPath}
          adding={addingVault}
          onAdd={handleAddVault}
          onDetect={detectAvailableVaults}
          onClose={() => setShowVaultSetup(false)}
        />
        {detectError && (
          <UnavailableState
            title="Vault detection is unavailable"
            message="No result is shown because the iCloud scan did not complete."
            onRetry={detectAvailableVaults}
          />
        )}
      </div>
    );
  }

  const notesKeyForView = `${selectedVaultId}\u0000${folderFilter}`;
  const hasCurrentNotes = notesKey === notesKeyForView;
  const currentNotes = hasCurrentNotes ? notes : [];

  // Build folder tree from notes
  const rootNotes = folderFilter
    ? currentNotes
    : currentNotes.filter(n => !n.folder);
  const folderNotes = folderFilter
    ? []
    : [...new Set(currentNotes.filter(n => n.folder).map(n => n.folder.split('/')[0]))];

  // Determine what to show in list
  const displayNotes = searchQuery ? (searchResults?.results || []) : currentNotes;

  return (
    <div className="grid grid-cols-1 md:grid-cols-[320px_1fr] grid-rows-1 h-full min-h-0 overflow-hidden">
      {/* Left panel: note list — on mobile it yields to the detail pane once a
          note is opened (the detail pane's back button restores it). On md+ both
          panels are always visible side-by-side. */}
      <div className={`border-r border-port-border flex-col min-h-0 overflow-hidden ${selectedNotePath || loadingNote || noteError ? 'hidden md:flex' : 'flex'}`}>
        {/* Vault selector and actions */}
        <div className="p-3 border-b border-port-border space-y-2">
          <div className="flex items-center gap-2">
            <select
              aria-label="Vault"
              value={selectedVaultId || ''}
              onChange={e => selectVault(e.target.value)}
              className="flex-1 min-w-0 min-h-[44px] bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white"
            >
              {vaults.map(v => (
                <option key={v.id} value={v.id}>{v.name}</option>
              ))}
            </select>
            <button
              onClick={() => setShowVaultSetup(true)}
              className="p-1.5 rounded hover:bg-port-card text-gray-400 hover:text-white min-h-[44px] min-w-[44px] flex items-center justify-center shrink-0"
              title="Manage vaults" aria-label="Manage vaults"
            >
              <Settings size={14} />
            </button>
            <button
              onClick={() => { setShowCreateForm(true); setNewNotePath(''); }}
              className="p-1.5 rounded hover:bg-port-card text-gray-400 hover:text-port-accent min-h-[44px] min-w-[44px] flex items-center justify-center shrink-0"
              title="New note" aria-label="New note"
            >
              <Plus size={14} />
            </button>
          </div>

          {/* Search */}
          <div className="relative">
            <Search size={14} className="absolute left-2 top-1/2 -translate-y-1/2 text-gray-500" />
            <input
              ref={searchRef}
              value={searchInput}
              onChange={e => setSearchInput(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && handleSearch()}
              placeholder="Search notes..."
              aria-label="Search notes"
              className="w-full min-h-[44px] bg-port-bg border border-port-border rounded pl-7 pr-14 py-1.5 text-sm text-white placeholder-gray-500"
            />
            {searchInput && (
              <button
                onClick={clearSearch}
                aria-label="Clear search"
                className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-500 hover:text-white min-h-[44px] min-w-[44px] flex items-center justify-center"
              >
                <X size={14} />
              </button>
            )}
          </div>

          {/* Create note form */}
          {showCreateForm && (
            <div className="flex items-center gap-1">
              <input
                value={newNotePath}
                onChange={e => setNewNotePath(e.target.value)}
                onKeyDown={e => e.key === 'Enter' && handleCreateNote()}
                placeholder="folder/note-name"
                aria-label="New note path"
                className="flex-1 min-w-0 min-h-[44px] bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white placeholder-gray-500"
                autoFocus
              />
              <button
                onClick={handleCreateNote}
                disabled={creating || !newNotePath.trim()}
                className="px-3 min-h-[44px] min-w-[44px] shrink-0 rounded bg-port-accent text-white text-xs disabled:opacity-50"
              >
                {creating ? '...' : 'Create'}
              </button>
              <button
                onClick={() => setShowCreateForm(false)}
                aria-label="Close"
                className="p-1 rounded hover:bg-port-card text-gray-400 min-h-[44px] min-w-[44px] shrink-0 flex items-center justify-center"
              >
                <X size={14} />
              </button>
            </div>
          )}
        </div>

        {vaultError && (
          <UnavailableState
            title="Vault list refresh failed"
            message="Showing the last successful vault list. Retry when the server is reachable."
            onRetry={() => loadVaults()}
          />
        )}

        <OfflineNotesNotice count={(hasCurrentNotes ? skippedNotes : 0) + (searchResults?.skippedUnavailable || 0)} className="mx-3 mt-2" />

        {/* Stats bar */}
        <div className="px-3 py-1.5 border-b border-port-border flex items-center gap-3 text-xs text-gray-500">
          <span>{formatCount(hasCurrentNotes ? totalNotes : 0)} notes</span>
          {folderFilter && (
            <button
              onClick={() => updateParams({ folder: null })}
              className="flex items-center gap-1 text-port-accent hover:text-white"
            >
              <X size={10} />
              {folderFilter}
            </button>
          )}
          {searchResults && (
            <span className="text-port-accent">{formatCount(searchResults.total)} results</span>
          )}
          <button
            onClick={() => { loadTags(); setShowTags(!showTags); }}
            className={`min-h-[44px] min-w-[44px] inline-flex items-center justify-center ml-auto p-0.5 rounded ${showTags ? 'text-port-accent' : 'text-gray-500 hover:text-white'}`}
            title="Tags" aria-label="Tags"
          >
            <Tag size={12} />
          </button>
          <button
            onClick={loadNotes}
            className="min-h-[44px] min-w-[44px] inline-flex items-center justify-center p-0.5 rounded text-gray-500 hover:text-white"
            title="Refresh" aria-label="Refresh"
          >
            <RefreshCw size={12} className={scanning ? 'animate-spin' : ''} />
          </button>
        </div>

        {/* Tags panel */}
        {showTags && tags.length > 0 && (
          <div className="px-3 py-2 border-b border-port-border flex flex-wrap gap-1 max-h-24 overflow-auto">
            {tags.map(t => (
              <span
                key={t.tag}
                className="px-1.5 py-0.5 rounded text-xs bg-port-accent/20 text-port-accent cursor-pointer hover:bg-port-accent/30"
                onClick={() => { setSearchInput(`#${t.tag}`); handleSearch(`#${t.tag}`); }}
                {...clickableProps(() => { setSearchInput(`#${t.tag}`); handleSearch(`#${t.tag}`); })}
                onKeyDown={onActivateKeyDown(() => { setSearchInput(`#${t.tag}`); handleSearch(`#${t.tag}`); })}
              >
                #{t.tag} <span className="text-gray-500">{t.count}</span>
              </span>
            ))}
          </div>
        )}

        {scanError && (
          <UnavailableState
            title="Notes are unavailable"
            message={hasCurrentNotes && notes.length > 0 ? 'Showing the last successful scan. Retry when the vault is reachable.' : 'The vault scan did not complete, so an empty list is not being shown.'}
            onRetry={loadNotes}
          />
        )}
        {searchError && (
          <UnavailableState
            title="Search is unavailable"
            message={searchResults ? 'Showing the last successful search results. Retry when search is reachable.' : 'The search did not complete, so no-match results are not being shown.'}
            onRetry={() => loadSearch(searchQuery)}
          />
        )}

        {/* Note list */}
        <div className="flex-1 overflow-auto">
          {scanning && (!hasCurrentNotes || notes.length === 0) && !searchQuery ? (
            <div className="flex items-center justify-center h-32 text-gray-500 text-sm">
              <BrailleSpinner /> Scanning vault...
            </div>
          ) : searching ? (
            <div className="flex items-center justify-center h-32 text-gray-500 text-sm">
              <BrailleSpinner /> Searching notes...
            </div>
          ) : (!searchQuery && scanError && (!hasCurrentNotes || notes.length === 0)) || (searchQuery && searchError && !searchResults) ? null : displayNotes.length === 0 ? (
            <div className="flex items-center justify-center h-32 px-4 text-center text-gray-500 text-sm">
              {searchQuery ? 'No matches found' : 'No notes yet — capture notes in your vault to enrich Ask Yourself and your digital twin.'}
            </div>
          ) : (
            <div className="divide-y divide-port-border/50">
              {/* Folders first (when not searching) */}
              {!searchQuery && !folderFilter && folderNotes.map(folder => (
                <FolderItem
                  key={folder}
                  folder={folder}
                  notes={currentNotes.filter(n => n.folder === folder || n.folder.startsWith(folder + '/'))}
                  expanded={expandedFolders.has(folder)}
                  onToggle={() => toggleFolder(folder)}
                  onSelectNote={handleSelectNote}
                  onFilterFolder={() => updateParams({ folder })}
                  selectedPath={selectedNotePath}
                />
              ))}
              {/* Root notes or filtered/search results */}
              {(searchQuery ? displayNotes : rootNotes).map(note => (
                <NoteListItem
                  key={note.path}
                  note={note}
                  isSearch={Boolean(searchQuery)}
                  selected={selectedNotePath === note.path}
                  onClick={() => handleSelectNote(note.path)}
                />
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Right panel: note viewer/editor — hidden on mobile until a note is
          opened so the list owns the small-screen viewport; always shown on md+. */}
      <div className={`flex-col min-w-0 min-h-0 overflow-hidden ${selectedNotePath || loadingNote || noteError ? 'flex' : 'hidden md:flex'}`}>
        <NoteDetailPane
          selectedNote={selectedNote} loading={loadingNote} error={noteError}
          onRetry={retryNote} onBack={closeNote} backLabel="Back to notes"
          headerBackLabel="Back"
          editing={editing} onSetEditing={setEditing} noteContent={noteContent}
          onSetContent={setNoteContent} saving={saving} onSave={handleSaveNote}
          confirmingDelete={selectedNote ? isConfirmingDelete(selectedNote.path) : false}
          onRequestDelete={requestDelete} onDelete={handleDeleteNote}
          onCancelDelete={cancelDelete} forceOffered={forceOffered}
          dismissForce={dismissForce}
          renderPreview={content => <MarkdownOutput content={content} linkifyText={noteLinkify(handleSelectNote)} />}
          renderLinks={note => (
            <>
              <LinkSection icon={<Link2 size={10} />} label="Links" items={note.wikilinks}
                getKey={link => link} getLabel={link => link}
                onClickItem={link => {
                  const match = notes.find(n => n.name.toLowerCase() === link.toLowerCase());
                  if (match) handleSelectNote(match.path);
                  else toast.warning(`Note "${link}" not found in vault`);
                }} />
              <LinkSection icon={<ArrowLeft size={10} />} label="Backlinks" items={note.backlinks}
                getKey={bl => bl.path} getLabel={bl => bl.name}
                onClickItem={bl => handleSelectNote(bl.path)} />
            </>
          )}
          emptyHint="or press + to create a new one"
        />
      </div>
    </div>
  );
}

// =============================================================================
// SUB-COMPONENTS
// =============================================================================

function LinkSection({ icon, label, items, getKey, getLabel, onClickItem }) {
  if (!items?.length) return null;
  return (
    <div>
      <h4 className="text-xs font-medium text-gray-400 uppercase mb-1 flex items-center gap-1">
        {icon} {label} ({items.length})
      </h4>
      <div className="space-y-0.5">
        {items.map(item => (
          <button
            key={getKey(item)}
            onClick={() => onClickItem(item)}
            className="block w-full text-left text-xs text-port-accent hover:text-white truncate"
          >
            {getLabel(item)}
          </button>
        ))}
      </div>
    </div>
  );
}

function VaultSetup({ detectedVaults, vaults, customPath, setCustomPath, adding, onAdd, onDetect, onClose }) {
  return (
    <div className="max-w-2xl mx-auto space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-lg font-bold text-white flex items-center gap-2">
            <BookOpen size={20} className="text-port-accent" />
            Obsidian Vault Manager
          </h2>
          <p className="text-sm text-gray-500 mt-1">
            Connect your Obsidian vaults from iCloud to browse, search, and manage your notes.
          </p>
        </div>
        {vaults.length > 0 && (
          <button onClick={onClose} aria-label="Close" className="p-1.5 rounded hover:bg-port-card text-gray-400 hover:text-white min-h-[44px] min-w-[44px] flex items-center justify-center">
            <X size={16} />
          </button>
        )}
      </div>

      {/* Connected vaults */}
      {vaults.length > 0 && (
        <div>
          <h3 className="text-sm font-medium text-gray-400 mb-2">Connected Vaults</h3>
          {/* No remove affordance on these rows: VaultSetup is never handed a
              delete handler, and an inert trash button is worse than none — it
              is focusable, unlabeled, and implies an action that never runs. */}
          <div className="space-y-2">
            {vaults.map(v => (
              <div key={v.id} className="p-3 rounded-lg bg-port-card border border-port-border">
                <span className="text-white font-medium">{v.name}</span>
                <span className="text-xs text-gray-500 block truncate">{v.path}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Detected vaults from iCloud */}
      {detectedVaults.length > 0 && (
        <div>
          <h3 className="text-sm font-medium text-gray-400 mb-2">
            Detected iCloud Vaults
          </h3>
          <div className="space-y-2">
            {detectedVaults.map(dv => {
              const isConnected = vaults.some(v => v.path === dv.path);
              return (
                <div key={dv.path} className="flex items-center justify-between p-3 rounded-lg bg-port-card border border-port-border">
                  <div>
                    <span className="text-white">{dv.name}</span>
                    <span className="text-xs text-gray-500 block truncate">{dv.path}</span>
                  </div>
                  {isConnected ? (
                    <span className="text-xs text-port-success">Connected</span>
                  ) : (
                    <button
                      onClick={() => onAdd(dv.name, dv.path)}
                      disabled={adding}
                      className="px-3 py-1 rounded bg-port-accent text-white text-sm disabled:opacity-50"
                    >
                      {adding ? '...' : 'Connect'}
                    </button>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      )}

      {detectedVaults.length === 0 && vaults.length === 0 && (
        <div className="p-4 rounded-lg bg-port-card border border-port-border text-center">
          <p className="text-gray-400 text-sm mb-2">No Obsidian vaults found in iCloud.</p>
          <button
            onClick={onDetect}
            className="text-port-accent text-sm hover:text-white"
          >
            Scan again
          </button>
        </div>
      )}

      {/* Custom path */}
      <div>
        <h3 className="text-sm font-medium text-gray-400 mb-2">Add Custom Path</h3>
        <div className="flex items-center gap-2">
          <input
            value={customPath}
            onChange={e => setCustomPath(e.target.value)}
            placeholder="/path/to/obsidian/vault"
            aria-label="Custom vault path"
            className="flex-1 min-w-0 bg-port-bg border border-port-border rounded px-3 py-2 text-sm text-white placeholder-gray-500"
          />
          <FolderPicker
            value={customPath}
            onChange={setCustomPath}
            defaultPath="~/Library/Mobile Documents/iCloud~md~obsidian/Documents"
          />
          <button
            onClick={() => {
              if (customPath.trim()) {
                onAdd(null, customPath.trim());
                setCustomPath('');
              }
            }}
            disabled={adding || !customPath.trim()}
            className="px-4 py-2 rounded bg-port-accent text-white text-sm disabled:opacity-50"
          >
            Add
          </button>
        </div>
      </div>
    </div>
  );
}

function FolderItem({ folder, notes, expanded, onToggle, onSelectNote, onFilterFolder, selectedPath }) {
  return (
    <div>
      <button
        onClick={onToggle}
        className="w-full flex items-center gap-2 px-3 py-2 text-sm text-gray-400 hover:text-white hover:bg-port-card/50"
      >
        {expanded ? <ChevronDown size={12} /> : <ChevronRight size={12} />}
        <FolderOpen size={14} className="text-port-warning/60" />
        <span className="flex-1 text-left truncate">{folder}</span>
        <span className="text-xs text-gray-600">{notes.length}</span>
      </button>
      {expanded && (
        <div className="ml-4">
          {notes.slice(0, 20).map(note => (
            <NoteListItem
              key={note.path}
              note={note}
              selected={selectedPath === note.path}
              onClick={() => onSelectNote(note.path)}
              compact
            />
          ))}
          {notes.length > 20 && (
            <button
              onClick={onFilterFolder}
              className="w-full px-3 py-1 text-xs text-port-accent hover:text-white"
            >
              Show all {formatCount(notes.length)} notes...
            </button>
          )}
        </div>
      )}
    </div>
  );
}

function NoteListItem({ note, selected, onClick, compact, isSearch }) {
  return (
    <button
      onClick={onClick}
      className={`w-full text-left px-3 ${compact ? 'py-1.5' : 'py-2'} hover:bg-port-card/50 transition-colors ${
        selected ? 'bg-port-accent/10 border-l-2 border-port-accent' : ''
      }`}
    >
      <div className="flex items-center gap-2">
        <FileText size={12} className="text-gray-500 shrink-0" />
        <span className={`text-sm truncate ${selected ? 'text-white' : 'text-gray-300'}`}>
          {note.name}
        </span>
      </div>
      {!compact && (
        <div className="flex items-center gap-2 mt-0.5 ml-5">
          {isSearch && note.folder && (
            <span className="text-xs text-gray-600 truncate">{note.folder}/</span>
          )}
          {note.tags?.length > 0 && (
            <span className="text-xs text-gray-600 truncate">
              {note.tags.slice(0, 3).map(t => `#${t}`).join(' ')}
            </span>
          )}
          {isSearch && note.snippets?.[0] && (
            <span className="text-xs text-gray-600 truncate">
              ...{note.snippets[0].text.slice(0, 80)}...
            </span>
          )}
        </div>
      )}
    </button>
  );
}

// Note-specific inline syntax the shared renderer leaves as literal text:
// `[[target|display]]` opens that vault note in place, and `#tag` gets the
// accent tint. Everything else — including href vetting for `[text](url)` —
// is MarkdownOutput's.
const NOTE_INLINE_RE = /(\[\[[^\]|]+(?:\|[^\]]+)?\]\]|(?<=^|\s)#[a-zA-Z][a-zA-Z0-9_/-]*)/;

function noteLinkify(onLinkClick) {
  return text => text.split(NOTE_INLINE_RE).filter(Boolean).map(seg => {
    const wiki = seg.match(/^\[\[([^\]|]+)(?:\|([^\]]+))?\]\]$/);
    if (wiki) {
      const target = wiki[1].trim();
      return { ref: wiki[2]?.trim() || target, onClick: () => onLinkClick?.(`${target}.md`) };
    }
    if (seg[0] === '#') return { ref: seg, className: 'text-port-accent/70' };
    return seg;
  });
}