Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

56.0 KB
Raw Blame
import { isSameItem, scopedKey } from '@aliasvault/client/database/ItemRef';
import { CredentialSortOrder } from '@aliasvault/client/database/repositories/SettingsRepository';
import { canHaveSubfolders, getDescendantFolderIds, getFolderPath, getRecursiveItemCount, isItemInFolder, isSharedFolder } from '@aliasvault/client/items/FolderUtils';
import { ItemFilter, applySearchFilter, applyTypeFilter, isItemTypeFilter, parseItemFilterType, type ItemFilterType } from '@aliasvault/client/items/ItemFilters';
import { multiManifestRendering } from '@aliasvault/client/sharing/MultiManifestRendering';
import { SharingService } from '@aliasvault/client/sharing/SharingService';
import { canAdministerGroup, sharingText, holdsManifestKey, MAX_SHARED_VAULT_NAME_LENGTH } from '@aliasvault/client/sharing/SharingView';
import React, { useState, useEffect, useCallback, useDeferredValue, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';

import ConfirmDeleteModal from '@/entrypoints/popup/components/Dialogs/ConfirmDeleteModal';
import DeleteFolderModal from '@/entrypoints/popup/components/Folders/DeleteFolderModal';
import FolderBreadcrumb from '@/entrypoints/popup/components/Folders/FolderBreadcrumb';
import FolderModal from '@/entrypoints/popup/components/Folders/FolderModal';
import HeaderButton from '@/entrypoints/popup/components/HeaderButton';
import { HeaderIconType } from '@/entrypoints/popup/components/Icons/HeaderIcons';
import Icon from '@/entrypoints/popup/components/Icons/Icon';
import AddItemDropdown from '@/entrypoints/popup/components/Items/AddItemDropdown';
import CurrentSiteSuggestion from '@/entrypoints/popup/components/Items/CurrentSiteSuggestion';
import FolderPill from '@/entrypoints/popup/components/Items/FolderPill';
import ItemCard from '@/entrypoints/popup/components/Items/ItemCard';
import ItemFilterDropdown from '@/entrypoints/popup/components/Items/ItemFilterDropdown';
import { ITEM_TYPE_OPTIONS } from '@/entrypoints/popup/components/Items/ItemTypeSelector';
import LoadingSpinner from '@/entrypoints/popup/components/LoadingSpinner';
import ReloadButton from '@/entrypoints/popup/components/ReloadButton';
import SharedFolderAccessModal from '@/entrypoints/popup/components/Sharing/SharedFolderAccessModal';
import SharedFolderInvitationModal from '@/entrypoints/popup/components/Sharing/SharedFolderInvitationModal';
import { useDb } from '@/entrypoints/popup/context/DbContext';
import { useHeaderButtons } from '@/entrypoints/popup/context/HeaderButtonsContext';
import { useLoading } from '@/entrypoints/popup/context/LoadingContext';
import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';
import { useListKeyboardNav } from '@/entrypoints/popup/hooks/useListKeyboardNav';
import { usePasswordConfirmedAction } from '@/entrypoints/popup/hooks/usePasswordConfirmedAction';
import { useSharedFolders } from '@/entrypoints/popup/hooks/useSharedFolders';
import { useVaultMutate } from '@/entrypoints/popup/hooks/useVaultMutate';
import { useVaultRefresh } from '@/entrypoints/popup/hooks/useVaultRefresh';
import { PopoutUtility } from '@/entrypoints/popup/utils/PopoutUtility';
import { sharingFailureMessage, unwrapSharingResult } from '@/entrypoints/popup/utils/SharingErrors';

import { devLog } from '@/utils/devLogger/DevLogger';
import { itemRoute } from '@/utils/ItemRoute';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';

import { useMinDurationLoading } from '@/hooks/useMinDurationLoading';

import type { ItemRef } from '@aliasvault/client/database/ItemRef';
import type { Folder, FolderRef } from '@aliasvault/client/database/repositories/FolderRepository';
import type { Item, ItemType } from '@aliasvault/models/vault';

const FILTER_STORAGE_KEY = 'items-filter';
const FILTER_EXPIRY_MS = 5 * 60 * 1000; // 5 minutes

/*
 * Minimum number of vault entries before the current-site suggestion is shown.
 * With only a handful of entries (e.g. right after onboarding) the whole list is
 * already visible, so a suggestion just duplicates an entry that's right there.
 */
const CURRENT_SITE_SUGGESTION_MIN_ITEMS = 5;

/**
 * How many items render per infinite scroll batch, so a large vault does not render thousands of item cards at once.
 */
const ITEM_BATCH_SIZE = 200;

/**
 * Sort order options with their translation keys
 */
const SORT_OPTIONS: { value: CredentialSortOrder; labelKey: string }[] = [
  { value: CredentialSortOrder.OldestFirst, labelKey: 'items.sort.oldestFirst' },
  { value: CredentialSortOrder.NewestFirst, labelKey: 'items.sort.newestFirst' },
  { value: CredentialSortOrder.Alphabetical, labelKey: 'items.sort.alphabetical' },
];

/**
 * Get stored filter from localStorage if not expired
 */
const getStoredFilter = (): ItemFilterType => {
  try {
    const stored = localStorage.getItem(FILTER_STORAGE_KEY);
    if (!stored) {
      return ItemFilter.All;
    }

    const { filter, timestamp } = JSON.parse(stored);
    const now = Date.now();

    // Check if expired (5 minutes)
    if (now - timestamp > FILTER_EXPIRY_MS) {
      localStorage.removeItem(FILTER_STORAGE_KEY);
      return ItemFilter.All;
    }

    return filter as ItemFilterType;
  } catch {
    return ItemFilter.All;
  }
};

/**
 * Store filter in localStorage with timestamp
 */
const storeFilter = (filter: ItemFilterType): void => {
  try {
    localStorage.setItem(FILTER_STORAGE_KEY, JSON.stringify({
      filter,
      timestamp: Date.now()
    }));
  } catch {
    // Ignore storage errors
  }
};

/**
 * Represents a folder with item count
 */
type FolderWithCount = {
  id: string;
  manifestId: string;
  name: string;
  itemCount: number;
  isShared: boolean;
};

/**
 * Items list page with folder support.
 */
const ItemsList: React.FC = () => {
  const { t } = useTranslation();
  const { folderId: folderIdParam, manifestId: manifestIdParam } = useParams<{ folderId?: string; manifestId?: string }>();
  const location = useLocation();
  const [searchParams] = useSearchParams();
  const dbContext = useDb();
  const navigate = useNavigate();
  const refreshVault = useVaultRefresh();
  const { executeVaultMutationAsync } = useVaultMutate();
  const { setHeaderButtons, setBackButtonTitle } = useHeaderButtons();
  const [items, setItems] = useState<Item[]>([]);
  // Initialize searchTerm from URL query parameter (restored from back navigation or popup restore)
  const [searchTerm, setSearchTerm] = useState(() => {
    return searchParams.get('search') || '';
  });
  // URL filter takes precedence so navigating between folders preserves the active filter.
  const [filterType, setItemFilterType] = useState<ItemFilterType>(() => {
    const urlFilter = searchParams.get('filter');
    return urlFilter ? parseItemFilterType(urlFilter) : getStoredFilter();
  });
  const [showFolderModal, setShowFolderModal] = useState(false);
  const [showDeleteFolderModal, setShowDeleteFolderModal] = useState(false);
  const [showEditFolderModal, setShowEditFolderModal] = useState(false);
  const [deleteItem, setDeleteItem] = useState<ItemRef | null>(null);
  const [highlightedItem, setHighlightedItem] = useState<ItemRef | null>(null);
  const [recentlyDeletedCount, setRecentlyDeletedCount] = useState(0);
  const [folderRefreshKey, setFolderRefreshKey] = useState(0);
  const [sortOrder, setSortOrder] = useState<CredentialSortOrder>(CredentialSortOrder.NewestFirst);
  const [showSortMenu, setShowSortMenu] = useState(false);
  const [showFolders, setShowFolders] = useState(true);
  const [visibleItemCount, setVisibleItemCount] = useState(ITEM_BATCH_SIZE);
  /** The folder whose people dialog is open; kept while the folder turns into a shared one and the page moves to it. */
  const [peopleFolder, setPeopleFolder] = useState<{ folder: Pick<Folder, 'Id' | 'ManifestId' | 'Name'>; isShared: boolean } | null>(null);
  const [openInvitationId, setOpenInvitationId] = useState<string | null>(null);
  const shared = useSharedFolders();
  const webApi = useWebApi();
  const { askPassword, passwordModal } = usePasswordConfirmedAction();
  const { setIsInitialLoading } = useLoading();
  const searchInputRef = useRef<HTMLInputElement | null>(null);
  const sentinelRef = useRef<HTMLDivElement | null>(null);

  /*
   * The list filters on a deferred copy of the search term: the input updates on every keystroke right away, and
   * React filters and renders the list for the latest term when it has time, so typing never waits on the list.
   */
  const listSearchTerm = useDeferredValue(searchTerm);

  // Load showFolders preference from storage on mount
  useEffect(() => {
    LocalPreferencesService.getShowFolders().then(setShowFolders);
  }, []);

  // Derive current folder from URL params: a folder is only named by its manifest and its id together
  const currentFolderId = folderIdParam && manifestIdParam ? folderIdParam : null;
  const currentManifestId = currentFolderId ? manifestIdParam ?? null : null;
  const currentFolderRef = useMemo((): FolderRef | null => (currentFolderId && currentManifestId ? { Id: currentFolderId, ManifestId: currentManifestId } : null), [currentFolderId, currentManifestId]);

  // Get current folder name from database
  const currentFolderName = useMemo(() => {
    // folderRefreshKey is included in deps to force re-computation when folder is renamed
    void folderRefreshKey;
    if (!currentFolderRef || !dbContext?.sqliteClient) {
      return null;
    }
    const folders = dbContext.sqliteClient.folders.getAll();
    const folder = folders.find((f: Folder) => f.Id === currentFolderRef.Id && f.ManifestId === currentFolderRef.ManifestId);
    return folder?.Name ?? null;
  }, [currentFolderRef, dbContext?.sqliteClient, folderRefreshKey]);

  // The folder being viewed, re-read when it changes
  const currentFolder = useMemo(() => {
    // folderRefreshKey is included in deps to force re-computation when the folder changes
    void folderRefreshKey;
    if (!currentFolderRef || !dbContext?.sqliteClient) {
      return null;
    }

    return dbContext.sqliteClient.folders.getById(currentFolderRef);
  }, [currentFolderRef, dbContext?.sqliteClient, folderRefreshKey]);

  // A virtual folder (a shared manifest) is renamed and deleted through its shared folder, not as a stored folder.
  const currentFolderIsVirtual = currentFolder !== null && multiManifestRendering.isVirtualFolder(currentFolder);
  const currentShared = currentFolder !== null && currentFolderIsVirtual ? shared.folders.find(folder => folder.manifest.manifestId.toLowerCase() === currentFolder.ManifestId.toLowerCase()) ?? null : null;
  const canManageShared = currentShared !== null && canAdministerGroup(currentShared.group);
  const canRenameCurrent = !currentFolderIsVirtual || (currentShared !== null && canManageShared && holdsManifestKey(currentShared.manifest, shared.myUserId));
  const canDeleteCurrent = !currentFolderIsVirtual || canManageShared;
  // A top-level personal folder can be shared; a subfolder cannot, as a shared folder is always a top-level one.
  const canShareCurrent = shared.isEnabled && currentFolder !== null && (currentFolderIsVirtual || (currentFolder.ParentFolderId ?? null) === null);

  // Get current folder's full path (for relative path computation in search results)
  const currentFolderPath = useMemo(() => {
    if (!currentFolderRef || !dbContext?.sqliteClient) {
      return null;
    }
    const folders = dbContext.sqliteClient.folders.getAll();
    const path = getFolderPath(currentFolderRef, folders);
    return path.length > 0 ? path : null;
  }, [currentFolderRef, dbContext?.sqliteClient]);

  /**
   * Loading state with minimum duration for more fluid UX.
   */
  const [isLoading, setIsLoading] = useMinDurationLoading(true, 100);

  /**
   * Update URL when search term changes to persist it in navigation history.
   * Preserves any existing filter param in the URL (set by folder navigation) — the
   * filter is initialized from the URL on mount and otherwise managed in state, so
   * we just leave whatever filter param is there alone.
   */
  useEffect(() => {
    const params = new URLSearchParams(location.search);
    if (searchTerm) {
      params.set('search', searchTerm);
    } else {
      params.delete('search');
    }
    const queryString = params.toString();
    const newUrl = queryString ? `${location.pathname}?${queryString}` : location.pathname;

    // Only update if the URL actually changed
    const currentUrl = location.pathname + location.search;
    if (newUrl !== currentUrl) {
      navigate(newUrl, { replace: true });
    }
  }, [searchTerm, location.pathname, location.search, navigate]);

  /**
   * Reset search and filter when navigating via the vault tab (with resetFilters state).
   */
  useEffect(() => {
    const state = location.state as { resetFilters?: boolean } | null;
    if (state?.resetFilters) {
      setSearchTerm('');
      setItemFilterType(ItemFilter.All);
      localStorage.removeItem(FILTER_STORAGE_KEY);
      // Clear the state to prevent re-triggering on subsequent renders
      navigate(location.pathname, { replace: true, state: {} });
    }
  }, [location.state, location.pathname, navigate]);

  /**
   * Handle add new item.
   * Navigate to add item page, pre-selecting the item type if filtering by type.
   * Also pre-selects the current folder if we're inside a folder.
   */
  const handleAddItem = useCallback((type: ItemType) : void => {
    const params = new URLSearchParams();
    params.set('type', type);

    // Pre-select the current folder if we're inside a folder
    if (currentFolderRef) {
      params.set('folderId', currentFolderRef.Id);
      params.set('folderManifestId', currentFolderRef.ManifestId);
    }

    navigate(`/items/add?${params.toString()}`);
  }, [navigate, currentFolderRef]);

  /**
   * Handle add new folder.
   */
  const handleAddFolder = useCallback(() : void => {
    setShowFolderModal(true);
  }, []);

  /**
   * Handle save folder.
   * Creates folder in current location (root or inside current folder).
   */
  const handleSaveFolder = useCallback(async (folderName: string) : Promise<void> => {
    if (!dbContext?.sqliteClient) {
      devLog('[Folders] No sqliteClient available, skipping the folder save');
      return;
    }

    await executeVaultMutationAsync(async () => {
      // Create folder in current location (no current folder means root)
      await dbContext.sqliteClient!.folders.create(folderName, currentFolderRef);
    });

    // Refresh items to show the new folder
    const results = dbContext.sqliteClient!.items.getAll();
    setItems(results);
  }, [dbContext, currentFolderRef, executeVaultMutationAsync]);

  /**
   * Duplicate an item via the item context menu.
   */
  const handleDuplicateItem = useCallback(async (source: ItemRef) : Promise<void> => {
    if (!dbContext?.sqliteClient) {
      return;
    }

    let newItem: ItemRef | null = null;
    await executeVaultMutationAsync(async () => {
      newItem = await dbContext.sqliteClient!.items.duplicate(source);
    });

    // Refresh items to show the new duplicate
    const results = dbContext.sqliteClient!.items.getAll();
    setItems(results);

    // Scroll to and briefly highlight the new duplicate so it's clear where it landed
    setHighlightedItem(newItem);
  }, [dbContext, executeVaultMutationAsync]);

  /**
   * Scroll the highlighted item (a freshly created duplicate) into view once it's
   * rendered, then clear the highlight after a short moment.
   */
  useEffect(() => {
    if (!highlightedItem) {
      return;
    }

    // Wait a frame so the re-rendered list contains the new item before scrolling.
    requestAnimationFrame(() => {
      document.querySelector(`[data-item-key="${scopedKey(highlightedItem.ManifestId, highlightedItem.Id)}"]`)?.scrollIntoView({ behavior: 'smooth', block: 'center' });
    });

    const timer = setTimeout(() => setHighlightedItem(null), 2000);
    return (): void => clearTimeout(timer);
  }, [highlightedItem]);

  /**
   * Move an item to the trash after confirmation via the item context menu.
   */
  const handleConfirmDeleteItem = useCallback(async () : Promise<void> => {
    if (!dbContext?.sqliteClient || !deleteItem) {
      return;
    }

    const target = deleteItem;
    setDeleteItem(null);

    await executeVaultMutationAsync(async () => {
      await dbContext.sqliteClient!.items.trash(target);
    });

    // Refresh items to reflect the deletion
    const results = dbContext.sqliteClient!.items.getAll();
    setItems(results);
    const deletedCount = dbContext.sqliteClient!.items.getRecentlyDeletedCount();
    setRecentlyDeletedCount(deletedCount);
  }, [dbContext, deleteItem, executeVaultMutationAsync]);

  /**
   * Handle delete folder (keep items, move them to root).
   */
  const handleDeleteFolderOnly = useCallback(async () : Promise<void> => {
    if (!dbContext?.sqliteClient || !currentFolderRef) {
      return;
    }

    // Get the current folder to determine parent before deletion
    const parentFolderId = dbContext.sqliteClient.folders.getById(currentFolderRef)?.ParentFolderId ?? null;

    await executeVaultMutationAsync(async () => {
      await dbContext.sqliteClient!.folders.delete(currentFolderRef);
    });

    // Refresh items list to reflect changes
    const results = dbContext.sqliteClient!.items.getAll();
    setItems(results);
    const deletedCount = dbContext.sqliteClient!.items.getRecentlyDeletedCount();
    setRecentlyDeletedCount(deletedCount);

    // Navigate to parent folder if it exists, otherwise root
    if (parentFolderId) {
      navigate(`/items/folder/${currentFolderRef.ManifestId}/${parentFolderId}`);
    } else {
      navigate('/items');
    }
  }, [dbContext, currentFolderRef, executeVaultMutationAsync, navigate]);

  /**
   * Handle delete folder and all its contents.
   */
  const handleDeleteFolderAndContents = useCallback(async () : Promise<void> => {
    if (!dbContext?.sqliteClient || !currentFolderRef) {
      return;
    }

    // Get the current folder to determine parent before deletion
    const parentFolderId = dbContext.sqliteClient.folders.getById(currentFolderRef)?.ParentFolderId ?? null;

    await executeVaultMutationAsync(async () => {
      await dbContext.sqliteClient!.folders.deleteWithContents(currentFolderRef);
    });

    // Refresh items list to reflect changes
    const results = dbContext.sqliteClient!.items.getAll();
    setItems(results);
    const deletedCount = dbContext.sqliteClient!.items.getRecentlyDeletedCount();
    setRecentlyDeletedCount(deletedCount);

    // Navigate to parent folder if it exists, otherwise root
    if (parentFolderId) {
      navigate(`/items/folder/${currentFolderRef.ManifestId}/${parentFolderId}`);
    } else {
      navigate('/items');
    }
  }, [dbContext, currentFolderRef, executeVaultMutationAsync, navigate]);

  /**
   * Handle edit/rename folder.
   */
  const handleEditFolder = useCallback(async (newName: string) : Promise<void> => {
    if (!dbContext?.sqliteClient || !currentFolderRef) {
      return;
    }

    await executeVaultMutationAsync(async () => {
      await dbContext.sqliteClient!.folders.update(currentFolderRef, newName);
    });

    // Trigger re-computation of currentFolderName
    setFolderRefreshKey(prev => prev + 1);

    // Close modal
    setShowEditFolderModal(false);
  }, [dbContext, currentFolderRef, executeVaultMutationAsync]);

  /**
   * Sync, then reopen the stored vault so the folders show what changed on the server.
   */
  const syncAndReload = useCallback(async (): Promise<void> => {
    await sendMessage('FULL_VAULT_SYNC', {});
    await dbContext.loadStoredDatabase();
  }, [dbContext]);

  /**
   * Rename the current shared folder: its name is encrypted with its key and kept on the server for every member.
   * Throws so the rename modal shows the error.
   */
  const handleRenameSharedFolder = useCallback(async (name: string): Promise<void> => {
    if (!currentShared) {
      return;
    }

    try {
      unwrapSharingResult(await sendMessage('GROUP_UPDATE_VAULT', { groupId: currentShared.group.groupId, manifestId: currentShared.manifest.manifestId, details: { name } }));
    } catch (renameError) {
      throw new Error(sharingFailureMessage(renameError, t('common.errors.unknownErrorTryAgain')));
    }

    await syncAndReload();
    setFolderRefreshKey(prev => prev + 1);
    await shared.reload();
  }, [currentShared, syncAndReload, shared, t]);

  /**
   * Delete the current shared folder for everyone, after a confirmation and the master password.
   */
  const handleDeleteSharedFolder = (): void => {
    if (!currentShared) {
      return;
    }

    const name = currentFolderName ?? '';
    askPassword({
      title: sharingText.deleteVault,
      confirmMessage: sharingText.deleteVaultConfirm(name),
      confirmText: t('common.delete'),
      description: sharingText.deleteVaultPasswordPrompt(name),
      failureMessage: sharingText.errors.deleteVaultFailed,
      /**
       * Run the deletion with the password proof.
       * @param answerChallenge - answers the SRP challenge.
       */
      perform: answerChallenge => SharingService.deleteSharedManifest(webApi, currentShared.group.groupId, currentShared.manifest.manifestId, answerChallenge),
      /**
       * Sync the deletion in and go to the vault's top level.
       */
      onDone: async () => {
        await syncAndReload();
        await shared.reload();
        navigate('/items');
      },
    });
  };

  /**
   * Finish an answered invitation: an accepted one is synced in (the background already synced) and opened.
   * @param manifestId - the shared folder the invitation was for.
   * @param accepted - whether it was accepted.
   */
  const finishInvitation = async (manifestId: string, accepted: boolean): Promise<void> => {
    setOpenInvitationId(null);
    if (accepted) {
      await dbContext.loadStoredDatabase();
      const id = manifestId.toLowerCase();
      navigate(`/items/folder/${id}/${id}?filter=${encodeURIComponent(filterType)}`);
    }
    await shared.reload();
  };

  // Set header buttons on mount and clear on unmount
  useEffect((): (() => void) => {
    const headerButtonsJSX = (
      <div className="flex items-center gap-2">
        {!PopoutUtility.isPopup() && (
          <HeaderButton
            onClick={() => PopoutUtility.openInNewPopup()}
            title={t('common.openInNewWindow')}
            iconType={HeaderIconType.EXPAND}
          />
        )}
        <AddItemDropdown onSelect={handleAddItem} />
      </div>
    );

    setHeaderButtons(headerButtonsJSX);
    return () => setHeaderButtons(null);
  }, [setHeaderButtons, handleAddItem, t]);

  // Set back button title for folder view
  useEffect(() => {
    if (currentFolderRef && dbContext?.sqliteClient) {
      const currentFolder = dbContext.sqliteClient.folders.getById(currentFolderRef);

      if (currentFolder && currentFolder.ParentFolderId) {
        // Has parent folder - show parent folder name, looked up inside the same manifest
        const parentFolder = dbContext.sqliteClient.folders.getById({ Id: currentFolder.ParentFolderId, ManifestId: currentFolderRef.ManifestId });
        if (parentFolder) {
          setBackButtonTitle(parentFolder.Name);
        } else {
          setBackButtonTitle(t('items.title'));
        }
      } else if (currentFolder) {
        // Root folder - show "Items"
        setBackButtonTitle(t('items.title'));
      } else {
        // Folder not found - fallback to "Items"
        setBackButtonTitle(t('items.title'));
      }
    }

    return (): void => setBackButtonTitle(null);
  }, [currentFolderRef, dbContext?.sqliteClient, setBackButtonTitle, t]);

  /**
   * Load items list on mount and on sqlite client change.
   */
  useEffect(() => {
    /**
     * Refresh items list when a (new) sqlite client is available.
     */
    const refreshItems = async () : Promise<void> => {
      if (dbContext?.sqliteClient) {
        setIsLoading(true);
        const results = dbContext.sqliteClient?.items.getAll() ?? [];
        setItems(results);
        // Also get recently deleted count
        const deletedCount = dbContext.sqliteClient?.items.getRecentlyDeletedCount() ?? 0;
        setRecentlyDeletedCount(deletedCount);
        // Load sort order from settings
        const savedSortOrder = dbContext.sqliteClient?.settings.getCredentialsSortOrder() ?? CredentialSortOrder.NewestFirst;
        setSortOrder(savedSortOrder);
        setIsLoading(false);
        setIsInitialLoading(false);
      }
    };

    refreshItems();
  }, [dbContext?.sqliteClient, setIsLoading, setIsInitialLoading]);

  /**
   * Get the title based on the active filter and current folder.
   * An active filter takes precedence over the folder name so the title matches the
   * filter that's actually being applied — same behavior as the root view.
   */
  const getFilterTitle = () : string => {
    switch (filterType) {
      case ItemFilter.Passkeys:
        return t('common.passkeys');
      case ItemFilter.Attachments:
        return t('common.attachments');
      case ItemFilter.Totp:
        return t('items.filters.totp');
      case ItemFilter.All:
        if (currentFolderId && currentFolderName) {
          return currentFolderName;
        }
        return t('items.title');
      default:
        // Check if it's an item type filter
        if (isItemTypeFilter(filterType)) {
          const itemTypeOption = ITEM_TYPE_OPTIONS.find(opt => opt.type === filterType);
          if (itemTypeOption) {
            return t(itemTypeOption.titleKey);
          }
        }
        if (currentFolderId && currentFolderName) {
          return currentFolderName;
        }
        return t('items.title');
    }
  };

  /**
   * Navigate into a folder via URL, preserving the active filter so the folder view
   * shows the same subset reflected in the folder pill's badge count.
   */
  const handleFolderClick = useCallback((folder: FolderRef) => {
    setSearchTerm(''); // Clear search when entering folder
    navigate(`/items/folder/${folder.ManifestId}/${folder.Id}?filter=${encodeURIComponent(filterType)}`);
  }, [navigate, filterType]);

  /**
   * Get folders with item counts.
   * - At root level: show only root folders (ParentFolderId IS NULL)
   * - Inside a folder: show only direct subfolders (ParentFolderId = currentFolderId)
   * - Counts include items in the folder AND all subfolders recursively
   * - Counts respect the active type/feature filter so the badge matches what the user sees inside.
   */
  const folders = useMemo((): FolderWithCount[] => {
    // folderRefreshKey is included in deps to force re-computation when a folder changes
    void folderRefreshKey;

    if (listSearchTerm) {
      return []; // Don't show folders when searching
    }

    if (!dbContext?.sqliteClient) {
      return [];
    }

    // Get all folders directly from the database
    const allFolders = dbContext.sqliteClient.folders.getAll();

    // Filter folders based on current location
    const relevantFolders = allFolders.filter((folder: Folder) => {
      if (currentFolderRef) {
        // Inside a folder: show only direct children, which live in the folder's own manifest
        return folder.ParentFolderId === currentFolderRef.Id && folder.ManifestId === currentFolderRef.ManifestId;
      } else {
        /*
         * At root: show only root-level folders
         * Check for both null and undefined since SQLite might return either
         */
        return folder.ParentFolderId === null || folder.ParentFolderId === undefined;
      }
    });

    // Count items per folder (direct items only) using items that pass the active filter
    const filteredForCounts = applyTypeFilter(items, filterType);
    const directFolderCounts = new Map<string, number>();
    filteredForCounts.forEach((item: Item) => {
      if (item.FolderId) {
        const key = scopedKey(item.ManifestId, item.FolderId);
        directFolderCounts.set(key, (directFolderCounts.get(key) || 0) + 1);
      }
    });

    /**
     * Recursively count items in a folder and all its subfolders.
     * @param folder - The folder to count items for
     * @returns Total count of items in this folder and all descendant folders
     */
    const getRecursiveItemCountLocal = (folder: FolderRef): number => {
      // Start with direct items in this folder
      let count = directFolderCounts.get(scopedKey(folder.ManifestId, folder.Id)) || 0;

      // Add counts from all child folders recursively
      const childFolderIds = getDescendantFolderIds(folder, allFolders);
      for (const childId of childFolderIds) {
        count += directFolderCounts.get(scopedKey(folder.ManifestId, childId)) || 0;
      }

      return count;
    };

    // Build result with recursive counts
    const personalManifestId = dbContext.sqliteClient.getPersonalManifestId();
    const result = relevantFolders.map((folder: Folder) => ({
      id: folder.Id,
      manifestId: folder.ManifestId,
      name: folder.Name,
      itemCount: getRecursiveItemCountLocal(folder),
      isShared: isSharedFolder(folder, personalManifestId)
    })).sort((a: { name: string }, b: { name: string }) => a.name.localeCompare(b.name));

    return result;
  }, [listSearchTerm, dbContext?.sqliteClient, currentFolderRef, items, filterType, folderRefreshKey]);

  /**
   * Filter items based on current view (folder, search, filter type)
   */
  const filteredItems = useMemo((): Item[] => {
    // Filter by current folder (if in folder view)
    let folderScoped: Item[];
    if (currentFolderRef !== null) {
      if (listSearchTerm) {
        // When searching inside a folder, include items in subfolders too
        const allFolders = dbContext?.sqliteClient?.folders.getAll() || [];
        const childFolderIds = getDescendantFolderIds(currentFolderRef, allFolders);
        const allFolderIds = [currentFolderRef.Id, ...childFolderIds];
        folderScoped = items.filter((item: Item) =>
          item.ManifestId === currentFolderRef.ManifestId && item.FolderId !== null && item.FolderId !== undefined && allFolderIds.includes(item.FolderId)
        );
      } else {
        // When not searching, only show direct items (not items in subfolders)
        folderScoped = items.filter((item: Item) => isItemInFolder(item, currentFolderRef));
      }
    } else if (!listSearchTerm && showFolders) {
      /*
       * When showing folders (checkbox ON): only show root items (exclude items in folders)
       * When not showing folders (checkbox OFF): show all items flat
       */
      folderScoped = items.filter((item: Item) => !item.FolderId);
    } else {
      folderScoped = items;
    }

    const typeFiltered = applyTypeFilter(folderScoped, filterType);

    return applySearchFilter(typeFiltered, listSearchTerm);
  }, [items, currentFolderRef, listSearchTerm, showFolders, filterType, dbContext?.sqliteClient]);

  /**
   * Sort the filtered items based on the current sort order.
   */
  const sortedItems = useMemo(() => {
    const itemsCopy = [...filteredItems];
    switch (sortOrder) {
      case CredentialSortOrder.NewestFirst:
        return itemsCopy.sort((a, b) =>
          new Date(b.CreatedAt || 0).getTime() - new Date(a.CreatedAt || 0).getTime()
        );
      case CredentialSortOrder.Alphabetical:
        return itemsCopy.sort((a, b) =>
          (a.Name || '').localeCompare(b.Name || '')
        );
      case CredentialSortOrder.OldestFirst:
      default:
        return itemsCopy.sort((a, b) =>
          new Date(a.CreatedAt || 0).getTime() - new Date(b.CreatedAt || 0).getTime()
        );
    }
  }, [filteredItems, sortOrder]);

  /**
   * Start again at the first batch whenever the list itself changes (search, filter, folder or sort order).
   */
  useEffect(() => {
    setVisibleItemCount(ITEM_BATCH_SIZE);
  }, [listSearchTerm, filterType, currentFolderRef, sortOrder, showFolders]);

  /*
   * The rendered part of the list. It always reaches a freshly duplicated item, so the highlight can scroll to it.
   */
  const highlightedIndex = useMemo(() => (highlightedItem ? sortedItems.findIndex(item => isSameItem(item, highlightedItem)) : -1), [sortedItems, highlightedItem]);
  const renderedItemCount = Math.max(visibleItemCount, highlightedIndex + 1);
  const visibleItems = useMemo(() => sortedItems.slice(0, renderedItemCount), [sortedItems, renderedItemCount]);
  const hasMoreItems = renderedItemCount < sortedItems.length;

  /**
   * Keep a highlighted item rendered after the highlight clears, instead of dropping it from the list again.
   */
  useEffect(() => {
    if (highlightedIndex >= 0) {
      setVisibleItemCount(count => Math.max(count, highlightedIndex + 1));
    }
  }, [highlightedIndex]);

  /**
   * Infinite scroll: render the next batch when the sentinel below the list comes into view.
   */
  useEffect(() => {
    const sentinel = sentinelRef.current;
    if (!sentinel || !hasMoreItems || isLoading) {
      return;
    }
    const observer = new IntersectionObserver((entries) => {
      if (entries.some(entry => entry.isIntersecting)) {
        setVisibleItemCount(count => count + ITEM_BATCH_SIZE);
      }
    });
    observer.observe(sentinel);
    return (): void => observer.disconnect();
  }, [hasMoreItems, visibleItemCount, isLoading]);

  /**
   * Calculate total item count including items in current folder and all child folders.
   * Used for the delete folder modal to show accurate count.
   */
  const totalItemCountInFolderTree = useMemo(() => {
    if (!currentFolderRef || !dbContext?.sqliteClient) {
      return filteredItems.length;
    }

    const allFolders = dbContext.sqliteClient.folders.getAll();
    return getRecursiveItemCount(currentFolderRef, items, allFolders);
  }, [currentFolderRef, items, dbContext?.sqliteClient, filteredItems.length]);

  /**
   * Check if the current folder can have subfolders (not at max depth).
   * At root level (currentFolderId = null), we can always create folders.
   */
  const canCreateSubfolder = useMemo(() => {
    if (!currentFolderRef) {
      return true; // Root level, always allowed
    }
    if (!dbContext?.sqliteClient) {
      return false;
    }
    const allFolders = dbContext.sqliteClient.folders.getAll();
    return canHaveSubfolders(currentFolderRef, allFolders);
  }, [currentFolderRef, dbContext?.sqliteClient]);

  /**
   * Check if all items are in folders (no items at root level but items exist in folders).
   * This is used to show a helpful message when the user has imported credentials that were all in folders.
   */
  const hasItemsInFoldersOnly = items.length > 0 && items.every((item: Item) => item.FolderId !== null);

  /**
   * Open the Nth item in the current sorted list (ArrowRight on an item).
   */
  const handleActivateItem = useCallback((index: number): void => {
    const item = sortedItems[index];
    if (!item) {
      return;
    }
    const url = searchTerm ? `${itemRoute(item)}?returnSearch=${encodeURIComponent(searchTerm)}` : itemRoute(item);
    navigate(url);
  }, [sortedItems, searchTerm, navigate]);

  /**
   * Enter the Nth folder (ArrowRight on a folder pill).
   */
  const handleActivateFolder = useCallback((index: number): void => {
    const folder = folders[index];
    if (!folder) {
      return;
    }
    handleFolderClick({ Id: folder.id, ManifestId: folder.manifestId });
  }, [folders, handleFolderClick]);

  /**
   * Clear the search input (ArrowUp inside the search field with text).
   */
  const handleClearSearch = useCallback((): void => {
    setSearchTerm('');
  }, []);

  /**
   * Go up one folder (ArrowLeft).
   */
  const handleGoBack = useCallback((): void => {
    if (!currentFolderRef || !dbContext?.sqliteClient) {
      return;
    }
    const parentFolderId = dbContext.sqliteClient.folders.getById(currentFolderRef)?.ParentFolderId ?? null;
    if (parentFolderId) {
      navigate(`/items/folder/${currentFolderRef.ManifestId}/${parentFolderId}`);
    } else {
      navigate('/items');
    }
  }, [currentFolderRef, dbContext, navigate]);

  const { activeKind, activeIndex, itemIdFor, folderIdFor, activeDescendantId } = useListKeyboardNav({
    folderCount: folders.length,
    itemCount: visibleItems.length,
    searchInputRef,
    resetKey: currentFolderRef ? scopedKey(currentFolderRef.ManifestId, currentFolderRef.Id) : null,
    onActivateFolder: handleActivateFolder,
    onActivateItem: handleActivateItem,
    onGoBack: handleGoBack,
    onClearSearch: handleClearSearch,
  });

  /**
   * Render the next batch while keyboard selection is still a few items from the end, so a held arrow-down keeps going.
   */
  useEffect(() => {
    if (activeKind === 'item' && activeIndex >= visibleItems.length - 10 && hasMoreItems) {
      setVisibleItemCount(count => count + ITEM_BATCH_SIZE);
    }
  }, [activeKind, activeIndex, visibleItems.length, hasMoreItems]);

  /* Invitations to shared folders wait in the folder list at the top level until they are answered. */
  const invitationPills = !currentFolderId && !searchTerm ? shared.invitations.map(invitation => (
    <button
      key={invitation.id}
      data-invitation={invitation.id}
      onClick={() => setOpenInvitationId(invitation.id)}
      className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-sm border border-dashed border-primary-400 bg-primary-50/50 text-gray-500 hover:bg-primary-50 dark:border-primary-600 dark:bg-primary-900/10 dark:text-gray-400 dark:hover:bg-primary-900/20 transition-colors"
    >
      <Icon name="mail" className="w-3.5 h-3.5 text-primary-500" />
      <span className="truncate max-w-[120px]">{shared.invitationNames[invitation.id] ?? sharingText.sharedVault}</span>
      <span className="text-xs text-primary-600 dark:text-primary-400">{sharingText.invitationPending}</span>
    </button>
  )) : [];

  const openInvitation = shared.invitations.find(candidate => candidate.id === openInvitationId) ?? null;

  if (isLoading) {
    return (
      <div className="flex justify-center items-center p-8">
        <LoadingSpinner />
      </div>
    );
  }

  return (
    <div>
      {/* Breadcrumb navigation - only show when inside a folder */}
      <FolderBreadcrumb folder={currentFolderRef} />

      <div className="flex justify-between items-center gap-2 mb-4">
        <div className="min-w-0 flex-1 flex items-center gap-2">
          <ItemFilterDropdown
            title={getFilterTitle()}
            count={filteredItems.length}
            titleFolder={filterType === ItemFilter.All && currentFolder && currentFolderName ? { isShared: isSharedFolder(currentFolder, dbContext.sqliteClient?.getPersonalManifestId()) } : undefined}
            activeFilter={filterType}
            recentlyDeletedCount={recentlyDeletedCount}
            showFoldersToggle={!currentFolderId}
            showFolders={showFolders}
            onToggleShowFolders={(next) => {
              setShowFolders(next);
              LocalPreferencesService.setShowFolders(next);
            }}
            onSelectFilter={(newFilter) => {
              setItemFilterType(newFilter);
              storeFilter(newFilter);
            }}
            onSelectRecentlyDeleted={() => navigate('/items/deleted')}
          />
          {/* People, edit and delete buttons; a shared folder is managed through its shared manifest */}
          {currentFolderId && currentFolder && (canShareCurrent || canRenameCurrent || canDeleteCurrent) && (
            <div className="flex items-center gap-1 shrink-0">
              {canShareCurrent && (
                <button
                  id="folder-people"
                  onClick={() => setPeopleFolder({ folder: currentFolder, isShared: currentFolderIsVirtual })}
                  title={sharingText.peopleTitle}
                  className="p-1.5 text-gray-400 hover:text-primary-500 dark:text-gray-500 dark:hover:text-primary-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
                >
                  <Icon name="users" className="w-4 h-4" />
                </button>
              )}
              {canRenameCurrent && (
                <button
                  onClick={() => setShowEditFolderModal(true)}
                  title={t('items.folders.editFolder')}
                  className="p-1.5 text-gray-400 hover:text-primary-500 dark:text-gray-500 dark:hover:text-primary-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
                >
                  <Icon name="pencil-alt" className="w-4 h-4" />
                </button>
              )}
              {canDeleteCurrent && (
                <button
                  onClick={() => (currentFolderIsVirtual ? handleDeleteSharedFolder() : setShowDeleteFolderModal(true))}
                  title={t('items.folders.deleteFolder')}
                  className="p-1.5 text-gray-400 hover:text-red-500 dark:text-gray-500 dark:hover:text-red-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
                >
                  <Icon name="trash" className="w-4 h-4" strokeWidth={1} />
                </button>
              )}
            </div>
          )}
        </div>
        <div className="flex items-center gap-1">
          {/* Sort button */}
          <div className="relative">
            <button
              onClick={() => setShowSortMenu(!showSortMenu)}
              className="p-1.5 text-gray-400 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
              title={t('items.sort.title')}
            >
              <Icon name="sort-descending" className="w-5 h-5" />
            </button>
            {showSortMenu && (
              <>
                <div
                  className="fixed inset-0 z-10"
                  onClick={() => setShowSortMenu(false)}
                />
                <div className="absolute right-0 top-full mt-1 w-48 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-xl ring-1 ring-black/5 dark:ring-white/10 z-20">
                  <div className="py-1">
                    {SORT_OPTIONS.map((option) => (
                      <button
                        key={option.value}
                        onClick={async () => {
                          setSortOrder(option.value);
                          setShowSortMenu(false);
                          // Save to settings and trigger vault sync
                          await executeVaultMutationAsync(async () => {
                            dbContext.sqliteClient?.settings.setCredentialsSortOrder(option.value);
                          });
                        }}
                        className={`w-full text-left px-4 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-700 flex items-center gap-2 ${
                          sortOrder === option.value ? 'text-primary-600 dark:text-primary-400' : 'text-gray-700 dark:text-gray-300'
                        }`}
                      >
                        {sortOrder === option.value ? (
                          <Icon name="check" className="w-4 h-4" />
                        ) : (
                          <span className="w-4" />
                        )}
                        <span>{t(option.labelKey)}</span>
                      </button>
                    ))}
                  </div>
                </div>
              </>
            )}
          </div>
          <ReloadButton onClick={() => void refreshVault()} />
        </div>
      </div>

      {items.length > 0 ? (
        <div className="mb-4">
          <input
            ref={searchInputRef}
            type="text"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            placeholder={`${t('items.searchPlaceholder')}`}
            autoFocus
            role="combobox"
            aria-controls="items-list"
            aria-expanded={sortedItems.length > 0 || folders.length > 0}
            aria-activedescendant={activeDescendantId}
            aria-autocomplete="list"
            className="w-full p-2 border dark:border-gray-600 rounded bg-white dark:bg-gray-800 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-1 focus:ring-primary-500 focus:border-primary-500"
          />
        </div>
      ) : (
        <></>
      )}

      {/* Current-site suggestion: show a suggestion for the current site's matching item(s) to quickly view/open them. */}
      {items.length > CURRENT_SITE_SUGGESTION_MIN_ITEMS && !currentFolderId && !searchTerm && filterType === ItemFilter.All && (
        <CurrentSiteSuggestion items={items} onSearch={setSearchTerm} />
      )}

      {items.length === 0 ? (
        <>
          {invitationPills.length > 0 && <div className="flex flex-wrap items-center gap-2 mb-4">{invitationPills}</div>}
          <div className="text-gray-500 dark:text-gray-400 space-y-2 mb-10">
            <p>
              {t('items.welcomeTitle')}
            </p>
            <p>
              {t('items.welcomeDescription')}
            </p>
          </div>
        </>
      ) : filteredItems.length === 0 && folders.length === 0 && !hasItemsInFoldersOnly && !currentFolderId ? (
        <div className="text-gray-500 dark:text-gray-400 space-y-3 mb-10">
          {/* Show filter/search-specific messages only when actively filtering or searching */}
          {(filterType !== ItemFilter.All || searchTerm) && (
            <>
              <p>
                {/* Different messages based on what's causing no results */}
                {searchTerm && filterType !== ItemFilter.All
                  // Both search and filter active
                  ? t('items.noMatchingItemsWithFilter', { filter: getFilterTitle(), search: searchTerm })
                  : searchTerm
                    // Only search active
                    ? t('items.noMatchingItemsSearch', { search: searchTerm })
                    // Only filter active (no search)
                    : filterType !== ItemFilter.All
                      ? t('items.noMatchingItems')
                      : t('items.noMatchingItems')
                }
              </p>
              {/* Clear filter/search buttons */}
              <div className="flex flex-wrap gap-2">
                {searchTerm && (
                  <button
                    onClick={() => setSearchTerm('')}
                    className="inline-flex items-center gap-1 px-3 py-1.5 text-sm bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300 rounded-lg transition-colors"
                  >
                    <Icon name="x" className="w-4 h-4" />
                    {t('items.clearSearch')}
                  </button>
                )}
                {filterType !== ItemFilter.All && (
                  <button
                    onClick={() => {
                      setItemFilterType(ItemFilter.All);
                      localStorage.removeItem(FILTER_STORAGE_KEY);
                    }}
                    className="inline-flex items-center gap-1 px-3 py-1.5 text-sm bg-primary-100 dark:bg-primary-900/30 hover:bg-primary-200 dark:hover:bg-primary-900/50 text-primary-700 dark:text-primary-300 rounded-lg transition-colors"
                  >
                    <Icon name="x" className="w-4 h-4" />
                    {t('items.clearFilter')}
                  </button>
                )}
              </div>
            </>
          )}
        </div>
      ) : hasItemsInFoldersOnly && filteredItems.length === 0 && !currentFolderId && !searchTerm ? (
        /* Show message when all items are in folders and we're at root level */
        <>
          {/* Folders as inline pills - only render wrapper if there are folders OR if we can create subfolders */}
          {(folders.length > 0 || canCreateSubfolder) && (
            <div className="flex flex-wrap items-center gap-2 mb-4" role="listbox" aria-label={t('items.title')}>
              {folders.map((folder, index) => (
                <FolderPill
                  key={scopedKey(folder.manifestId, folder.id)}
                  folder={folder}
                  onClick={() => handleFolderClick({ Id: folder.id, ManifestId: folder.manifestId })}
                  isActive={activeKind === 'folder' && activeIndex === index}
                  optionId={folderIdFor(index)}
                  isShared={folder.isShared}
                />
              ))}
              {invitationPills}
              {canCreateSubfolder && (
                <button
                  onClick={handleAddFolder}
                  className="inline-flex items-center gap-1 px-2.5 py-1.5 text-xs rounded-full transition-colors focus:outline-none text-gray-500 dark:text-gray-400 hover:text-primary-600 dark:hover:text-primary-400 hover:bg-gray-100 dark:hover:bg-gray-700/50"
                >
                  <Icon name="folder" className="w-3.5 h-3.5" />
                  <Icon name="plus" className="w-3 h-3 -ml-0.5" strokeWidth={2.5} />
                </button>
              )}
            </div>
          )}
          <div className="text-gray-500 dark:text-gray-400 text-sm">
            <p>{t('items.allItemsInFoldersClick')}</p>
          </div>
        </>
      ) : (
        <>
          {/* Folders as inline pills - show when not searching */}
          {/* At root: show only if showFolders is enabled */}
          {/* Inside folder: always show subfolders and create button */}
          {/* Only render wrapper if there are folders OR if we can create subfolders */}
          {!searchTerm && (currentFolderId || showFolders) && (folders.length > 0 || canCreateSubfolder) && (
            <div className="flex flex-wrap items-center gap-2 mb-4" role="listbox" aria-label={t('items.title')}>
              {folders.map((folder, index) => (
                <FolderPill
                  key={scopedKey(folder.manifestId, folder.id)}
                  folder={folder}
                  onClick={() => handleFolderClick({ Id: folder.id, ManifestId: folder.manifestId })}
                  isActive={activeKind === 'folder' && activeIndex === index}
                  optionId={folderIdFor(index)}
                  isShared={folder.isShared}
                />
              ))}
              {invitationPills}
              {canCreateSubfolder && (
                <button
                  onClick={handleAddFolder}
                  className={`inline-flex items-center gap-1 px-2.5 py-1.5 text-xs rounded-full transition-colors focus:outline-none ${
                    folders.length > 0
                      ? 'text-gray-500 dark:text-gray-400 hover:text-primary-600 dark:hover:text-primary-400 hover:bg-gray-100 dark:hover:bg-gray-700/50'
                      : 'text-gray-400 dark:text-gray-500 border border-dashed border-gray-300 dark:border-gray-600 hover:border-primary-400 dark:hover:border-primary-500 hover:text-primary-600 dark:hover:text-primary-400'
                  }`}
                >
                  <Icon name="folder" className="w-3.5 h-3.5" />
                  <Icon name="plus" className="w-3 h-3 -ml-0.5" strokeWidth={2.5} />
                  {folders.length === 0 && (
                    /**
                     * Only show text when there are no folders yet
                     * if there are folders we hide the text to save on UI space
                     */
                    <span>{t('items.folders.newFolder')}</span>
                  )}
                </button>
              )}
            </div>
          )}

          {/* Items */}
          {visibleItems.length > 0 && (
            <ul id="items-list" role="listbox" className="space-y-2">
              {visibleItems.map((item, index) => (
                <ItemCard
                  key={scopedKey(item.ManifestId, item.Id)}
                  item={item}
                  showFolderPath={!!listSearchTerm && !!item.FolderPath}
                  searchTerm={listSearchTerm}
                  currentFolderPath={currentFolderPath}
                  isActive={activeKind === 'item' && activeIndex === index}
                  optionId={itemIdFor(index)}
                  isHighlighted={highlightedItem !== null && isSameItem(item, highlightedItem)}
                  onDuplicate={handleDuplicateItem}
                  onDelete={setDeleteItem}
                />
              ))}
            </ul>
          )}

          {hasMoreItems && <div ref={sentinelRef} className="h-10" />}

          {/* Show help text when inside an empty folder with no items */}
          {currentFolderId && sortedItems.length === 0 && !searchTerm && (
            <div className="text-gray-500 dark:text-gray-400 text-sm mb-4">
              <p>{t('items.emptyFolderHint')}</p>
            </div>
          )}

          {/* Clear filter/search pills at bottom of list when filtering or searching */}
          {(filterType !== ItemFilter.All || searchTerm) && (
            <div className="flex flex-wrap justify-center gap-2 mt-4 pt-4">
              {searchTerm && (
                <button
                  onClick={() => setSearchTerm('')}
                  className="inline-flex items-center gap-1 px-3 py-1.5 text-sm bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-300 rounded-lg transition-colors"
                >
                  <Icon name="x" className="w-4 h-4" />
                  {t('items.clearSearch')}
                </button>
              )}
              {filterType !== ItemFilter.All && (
                <button
                  onClick={() => {
                    setItemFilterType(ItemFilter.All);
                    localStorage.removeItem(FILTER_STORAGE_KEY);
                  }}
                  className="inline-flex items-center gap-1 px-3 py-1.5 text-sm bg-primary-100 dark:bg-primary-900/30 hover:bg-primary-200 dark:hover:bg-primary-900/50 text-primary-700 dark:text-primary-300 rounded-lg transition-colors"
                >
                  <Icon name="x" className="w-4 h-4" />
                  {t('items.clearFilter')}
                </button>
              )}
            </div>
          )}
        </>
      )}

      {/* Delete Item Confirmation Modal */}
      <ConfirmDeleteModal
        isOpen={deleteItem !== null}
        onClose={() => setDeleteItem(null)}
        onConfirm={handleConfirmDeleteItem}
        title={t('items.deleteItem')}
        message={t('common.deleteItemConfirmDescription')}
        confirmText={t('common.delete')}
      />

      {/* Create Folder Modal */}
      <FolderModal
        isOpen={showFolderModal}
        onClose={() => setShowFolderModal(false)}
        onSave={handleSaveFolder}
        mode="create"
      />

      {/* Edit Folder Modal; a shared folder is renamed through its shared manifest, whose name an invitation has to fit */}
      <FolderModal
        isOpen={showEditFolderModal}
        onClose={() => setShowEditFolderModal(false)}
        onSave={currentFolderIsVirtual ? handleRenameSharedFolder : handleEditFolder}
        initialName={currentFolderName || ''}
        mode="edit"
        maxLength={currentFolderIsVirtual ? MAX_SHARED_VAULT_NAME_LENGTH : undefined}
      />

      {/* Delete Folder Modal */}
      <DeleteFolderModal
        isOpen={showDeleteFolderModal}
        onClose={() => setShowDeleteFolderModal(false)}
        onDeleteFolderOnly={handleDeleteFolderOnly}
        onDeleteFolderAndContents={handleDeleteFolderAndContents}
        itemCount={totalItemCountInFolderTree}
      />

      {peopleFolder && (
        <SharedFolderAccessModal
          folder={peopleFolder.folder}
          isShared={peopleFolder.isShared}
          shared={shared}
          onMoved={(ref, isShared) => {
            setPeopleFolder(open => (open ? { folder: { ...open.folder, Id: ref.Id, ManifestId: ref.ManifestId }, isShared } : null));
            // The contents moved inside the open vault, which does not reload the list by itself.
            setItems(dbContext.getSqliteClient()?.items.getAll() ?? []);
            setFolderRefreshKey(prev => prev + 1);
            navigate(`/items/folder/${ref.ManifestId}/${ref.Id}?filter=${encodeURIComponent(filterType)}`);
          }}
          onLeft={() => {
            setPeopleFolder(null);
            navigate('/items');
          }}
          onClose={() => setPeopleFolder(null)}
        />
      )}

      <SharedFolderInvitationModal
        invitation={openInvitation}
        folderName={openInvitation ? shared.invitationNames[openInvitation.id] ?? sharingText.sharedVault : ''}
        onDone={accepted => (openInvitation ? finishInvitation(openInvitation.manifestId, accepted) : Promise.resolve())}
        onClose={() => setOpenInvitationId(null)}
      />

      {passwordModal}
    </div>
  );
};

export default ItemsList;