Skip to content

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

33.8 KB
Raw Blame
import { scopedKey, type ItemRef } from '@aliasvault/client/database/ItemRef';
import { CredentialSortOrder } from '@aliasvault/client/database/repositories/SettingsRepository';
import { getRecursiveItemCount, isSharedFolder } from '@aliasvault/client/items/FolderUtils';
import { ItemFilter, applySearchFilter, applyTypeFilter, isItemTypeFilter, type ItemFilterType } from '@aliasvault/client/items/ItemFilters';
import { sharingText } from '@aliasvault/client/sharing/SharingView';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { useNavigation, useRouter, useLocalSearchParams } from 'expo-router';
import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { StyleSheet, Text, Platform, Animated, TextInput, TouchableOpacity, View, RefreshControl } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';

import type { DisplayItem } from '@/utils/DisplayItem';
import emitter from '@/utils/EventEmitter';
import { folderRoute } from '@/utils/FolderRoute';
import { HapticsUtility } from '@/utils/HapticsUtility';

import { useAppReviewPrompt } from '@/hooks/useAppReviewPrompt';
import { useColors } from '@/hooks/useColorScheme';
import { useMinDurationLoading } from '@/hooks/useMinDurationLoading';
import { useNavigationDebounce } from '@/hooks/useNavigationDebounce';
import { usePersonalManifestId } from '@/hooks/usePersonalManifestId';
import { useSharedFolders } from '@/hooks/useSharedFolders';
import { useVaultMutate } from '@/hooks/useVaultMutate';
import { useVaultRefresh } from '@/hooks/useVaultRefresh';
import { useVaultSync } from '@/hooks/useVaultSync';

import Logo from '@/assets/images/logo.svg';
import { FolderModal } from '@/components/folders/FolderModal';
import { FolderPill, type FolderWithCount } from '@/components/folders/FolderPill';
import { AddItemFab } from '@/components/items/AddItemFab';
import { ItemCard } from '@/components/items/ItemCard';
import { ItemFilterMenu } from '@/components/items/ItemFilterMenu';
import { SortMenu } from '@/components/items/SortMenu';
import { SharedFolderInvitationModal } from '@/components/sharing/SharedFolderInvitationModal';
import { ThemedContainer } from '@/components/themed/ThemedContainer';
import { ThemedText } from '@/components/themed/ThemedText';
import { ThemedView } from '@/components/themed/ThemedView';
import { AndroidHeader } from '@/components/ui/AndroidHeader';
import { CollapsibleHeader } from '@/components/ui/CollapsibleHeader';
import { SkeletonLoader } from '@/components/ui/SkeletonLoader';
import { useApp } from '@/context/AppContext';
import { useDb } from '@/context/DbContext';
import { LocalPreferencesService } from '@/services/LocalPreferencesService';

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

/**
 * Item type filter option configuration.
 */
type ItemTypeOption = {
  type: ItemFilterType;
  titleKey: string;
  iconName: keyof typeof MaterialIcons.glyphMap;
};

/**
 * Available item type filter options with icons.
 */
const ITEM_TYPE_OPTIONS: ItemTypeOption[] = [
  { type: ItemFilter.Login, titleKey: 'itemTypes.login.title', iconName: 'key' },
  { type: ItemFilter.Alias, titleKey: 'itemTypes.alias.title', iconName: 'person' },
  { type: ItemFilter.CreditCard, titleKey: 'itemTypes.creditCard.title', iconName: 'credit-card' },
  { type: ItemFilter.Note, titleKey: 'itemTypes.note.title', iconName: 'description' },
];

/**
 * Items screen - main vault items list.
 */
export default function ItemsScreen(): React.ReactNode {
  const { t } = useTranslation();
  const colors = useColors();
  const navigate = useNavigationDebounce();
  const [scrollY] = useState(() => new Animated.Value(0));
  const navigation = useNavigation();
  const insets = useSafeAreaInsets();
  const flatListRef = useRef<Animated.FlatList<DisplayItem | null>>(null);
  const [isTabFocused, setIsTabFocused] = useState(false);
  const router = useRouter();
  const { itemUrl } = useLocalSearchParams<{ itemUrl?: string }>();
  const [itemsList, setItemsList] = useState<DisplayItem[]>([]);
  const [folders, setFolders] = useState<Folder[]>([]);
  const personalManifestId = usePersonalManifestId();
  const [isLoadingItems, setIsLoadingItems] = useMinDurationLoading(false, 200);
  const [hasLoadedItems, setHasLoadedItems] = useState(false);
  const { executeVaultMutation } = useVaultMutate();
  const [showFolderModal, setShowFolderModal] = useState(false);
  const shared = useSharedFolders();
  const { syncVault } = useVaultSync();
  const [openInvitationId, setOpenInvitationId] = useState<string | null>(null);

  // Search and filter state
  const [searchQuery, setSearchQuery] = useState('');
  const [filterType, setFilterType] = useState<ItemFilterType>(ItemFilter.All);
  const [showFilterMenu, setShowFilterMenu] = useState(false);
  const [sortOrder, setSortOrder] = useState<CredentialSortOrder>(CredentialSortOrder.NewestFirst);
  const [showSortMenu, setShowSortMenu] = useState(false);
  const [showFolderItems, setShowFolderItems] = useState(true);

  // Recently deleted count state
  const [recentlyDeletedCount, setRecentlyDeletedCount] = useState(0);

  // Scoped key (manifest and id) of a freshly duplicated item that gets scrolled into view and briefly highlighted
  const [highlightedItemKey, setHighlightedItemKey] = useState<string | null>(null);

  const authContext = useApp();
  const dbContext = useDb();

  // Prompt for a store review when the app has been installed and used long enough and supported by the current platform.
  useAppReviewPrompt(hasLoadedItems);

  const isAuthenticated = authContext.isLoggedIn;
  const isDatabaseAvailable = dbContext.dbAvailable;

  /*
   * Handle deep link itemUrl parameter - populate search field.
   */
  useEffect(() => {
    if (itemUrl) {
      const decodedUrl = decodeURIComponent(itemUrl);
      // eslint-disable-next-line react-hooks/set-state-in-effect -- syncing search query with external deep-link parameter
      setSearchQuery(decodedUrl);
    }
  }, [itemUrl]);

  /*
   * Save search query to local storage whenever it changes.
   * This allows restoring it when navigating back from item details.
   */
  useEffect(() => {
    LocalPreferencesService.setLastSearchQuery(searchQuery);
  }, [searchQuery]);

  /*
   * Restore search query when screen gains focus (e.g., coming back from item details).
   */
  useEffect(() => {
    const unsubscribeFocus = navigation.addListener('focus', async () => {
      /*
       * Only restore search query if we don't have a deep link.
       * Deep links should take precedence.
       */
      if (!itemUrl) {
        const savedQuery = await LocalPreferencesService.getLastSearchQuery();
        if (savedQuery) {
          setSearchQuery(savedQuery);
        }
      }
    });

    return unsubscribeFocus;
  }, [navigation, itemUrl]);

  // Load saved showFolderItems preference from LocalPreferencesService
  useEffect(() => {
    /**
     * Load the show folders preference from LocalPreferencesService.
     */
    const loadShowFoldersPreference = async (): Promise<void> => {
      try {
        const stored = await LocalPreferencesService.getShowFolders();
        setShowFolderItems(stored);
      } catch {
        // Ignore storage errors, use default value
      }
    };
    loadShowFoldersPreference();
  }, []);

  /**
   * Get folders with item counts for display.
   * Counts respect the active type/feature filter so the folder badge always matches
   * the number of items the user will see when navigating into the folder.
   */
  const foldersWithCounts = useMemo((): FolderWithCount[] => {
    // Don't show folders when searching
    if (searchQuery) {
      return [];
    }

    // Apply the active type/feature filter to the items used for counting.
    const itemsForCount = applyTypeFilter(itemsList, filterType);

    // Return only root-level folders (no parent) with recursive counts, sorted alphabetically
    return folders
      .filter(folder => !folder.ParentFolderId) // Only root-level folders
      .map(folder => ({
        id: folder.Id,
        manifestId: folder.ManifestId,
        name: folder.Name,
        itemCount: getRecursiveItemCount(folder, itemsForCount, folders),
        isShared: isSharedFolder(folder, personalManifestId)
      }))
      .sort((a, b) => a.name.localeCompare(b.name));
  }, [folders, itemsList, searchQuery, filterType, personalManifestId]);

  /**
   * Get the title based on the active filter.
   */
  const getFilterTitle = useCallback((): 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:
        return t('items.title');
      default:
        if (isItemTypeFilter(filterType)) {
          const itemTypeOption = ITEM_TYPE_OPTIONS.find(opt => opt.type === filterType);
          if (itemTypeOption) {
            return t(itemTypeOption.titleKey);
          }
        }
        return t('items.title');
    }
  }, [filterType, t]);

  /**
   * 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 = useMemo(() => {
    return itemsList.length > 0 && itemsList.every((item: DisplayItem) => item.FolderId !== null);
  }, [itemsList]);

  /**
   * Filter items by folder, type, and search query.
   */
  const filteredItems = useMemo(() => {
    /*
     * When showing folders (checkbox ON): only show root items (exclude items in folders)
     * When not showing folders (checkbox OFF): show all items flat
     */
    const folderScoped = !searchQuery && showFolderItems
      ? itemsList.filter(item => !item.FolderId)
      : itemsList;

    const typeFiltered = applyTypeFilter(folderScoped, filterType);
    return applySearchFilter(typeFiltered, searchQuery);
  }, [itemsList, searchQuery, filterType, showFolderItems]);

  /**
   * 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]);

  /**
   * Load items (credentials), folders, and recently deleted count.
   */
  const loadItems = useCallback(async (): Promise<void> => {
    try {
      const [items, loadedFolders, deletedCount, savedSortOrder] = await Promise.all([
        dbContext.sqliteClient!.items.getAll(),
        dbContext.sqliteClient!.folders.getAll(),
        dbContext.sqliteClient!.items.getRecentlyDeletedCount(),
        dbContext.sqliteClient!.settings.getCredentialsSortOrder()
      ]);
      setItemsList(items);
      setFolders(loadedFolders);
      setRecentlyDeletedCount(deletedCount);
      setSortOrder(savedSortOrder);
      setIsLoadingItems(false);
      setHasLoadedItems(true);
    } catch (err) {
      console.error('Error loading items:', err);
      const errorMessage = err instanceof Error ? err.message : String(err);
      const errorStack = err instanceof Error ? err.stack ?? '' : '';
      router.replace({
        pathname: '/vault-error',
        params: { errorMessage, errorStack, errorSource: 'items' },
      });
    }
  }, [dbContext.sqliteClient, setIsLoadingItems, router]);

  useEffect(() => {
    const unsubscribeFocus = navigation.addListener('focus', () => {
      setIsTabFocused(true);
    });

    const unsubscribeBlur = navigation.addListener('blur', () => {
      setIsTabFocused(false);
    });

    const tabPressSub = emitter.addListener('tabPress', (routeName: string) => {
      if (routeName === 'items' && isTabFocused) {
        // Reset search and scroll to top when tapping the tab again
        setSearchQuery('');
        flatListRef.current?.scrollToOffset({ offset: 0, animated: true });
      }
    });

    // Add listener for item/credential changes
    const itemChangedSub = emitter.addListener('itemChanged', async () => {
      await loadItems();
    });
    const itemUsedSub = emitter.addListener('itemUsed', async () => {
      await loadItems();
    });

    return (): void => {
      tabPressSub.remove();
      itemChangedSub.remove();
      itemUsedSub.remove();
      unsubscribeFocus();
      unsubscribeBlur();
    };
  }, [isTabFocused, loadItems, navigation]);

  const { refreshing, onRefresh } = useVaultRefresh(loadItems, setIsLoadingItems);

  useEffect(() => {
    if (!isAuthenticated || !isDatabaseAvailable) {
      return;
    }

    setIsLoadingItems(true);
    // eslint-disable-next-line react-hooks/set-state-in-effect -- loadItems is async; setState only fires after data is fetched
    loadItems();
  }, [isAuthenticated, isDatabaseAvailable, loadItems, setIsLoadingItems]);

  /*
   * Reload once a sync completes, so newly synced data shows up without a manual pull-to-refresh.
   */
  useEffect(() => {
    const vaultSyncedSub = emitter.addListener('vaultSynced', () => {
      if (isAuthenticated && isDatabaseAvailable) {
        loadItems();
      }
    });

    return (): void => {
      vaultSyncedSub.remove();
    };
  }, [isAuthenticated, isDatabaseAvailable, loadItems]);

  // Set header for Android
  useEffect(() => {
    navigation.setOptions({
      /**
       * Define custom header which is shown on Android. iOS displays the custom CollapsibleHeader component instead.
       */
      headerTitle: (): React.ReactNode => {
        if (Platform.OS === 'android') {
          return (
            <AndroidHeader
              title={getFilterTitle()}
              subtitle={`(${filteredItems.length})`}
              onTitlePress={() => setShowFilterMenu(prev => !prev)}
              isDropdownOpen={showFilterMenu}
            />
          );
        }
        return <Text>{t('items.title')}</Text>;
      },
      /**
       * Sort button in the header (Android only, iOS uses inline button).
       */
      headerRight: (): React.ReactNode => {
        if (Platform.OS === 'android') {
          return (
            <TouchableOpacity
              style={{ padding: 8, marginRight: 8 }}
              onPress={() => setShowSortMenu(prev => !prev)}
            >
              <MaterialIcons name="sort" size={24} color={colors.text} />
            </TouchableOpacity>
          );
        }
        return null;
      },
    });
  }, [navigation, t, getFilterTitle, filteredItems.length, showFilterMenu, colors.text]);

  /**
   * Delete an item (move to trash).
   * Non-blocking: saves locally and syncs in background via ServerSyncIndicator.
   */
  const onItemDelete = useCallback(async (item: ItemRef): Promise<void> => {
    await executeVaultMutation(async () => {
      await dbContext.sqliteClient!.items.trash(item);
    });

    // Reload items to reflect the deletion
    await loadItems();
  }, [dbContext.sqliteClient, executeVaultMutation, loadItems]);

  /**
   * Duplicate an item including all fields except passkeys and field history.
   * Non-blocking: saves locally and syncs in background via ServerSyncIndicator.
   */
  const onItemDuplicate = useCallback(async (item: ItemRef): Promise<void> => {
    let duplicate: ItemRef | null = null;
    await executeVaultMutation(async () => {
      duplicate = await dbContext.sqliteClient!.items.duplicate(item);
    });

    // Reload items to show the new duplicate
    await loadItems();

    // Scroll to and briefly highlight the new duplicate so it's clear where it landed
    const created = duplicate as ItemRef | null;
    setHighlightedItemKey(created ? scopedKey(created.ManifestId, created.Id) : null);
  }, [dbContext.sqliteClient, executeVaultMutation, loadItems]);

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

    const index = sortedItems.findIndex(itm => scopedKey(itm.ManifestId, itm.Id) === highlightedItemKey);
    if (index >= 0) {
      flatListRef.current?.scrollToIndex({ index, viewPosition: 0.5, animated: true });
    }

    const timer = setTimeout(() => setHighlightedItemKey(null), 2000);
    return (): void => clearTimeout(timer);
  }, [highlightedItemKey, sortedItems]);

  /**
   * Navigate to a folder, preserving the active type/feature filter so the folder view
   * shows the same subset of items reflected in the folder's badge count.
   */
  const handleFolderClick = useCallback((folder: FolderRef) => {
    navigate(() => {
      router.push(folderRoute(folder, filterType));
    });
  }, [router, navigate, filterType]);

  /**
   * Finish an answered invitation: an accepted one is synced in and opened.
   * @param manifestId - the shared folder it was for.
   * @param accepted - whether it was accepted.
   */
  const finishInvitation = useCallback(async (manifestId: string, accepted: boolean): Promise<void> => {
    setOpenInvitationId(null);
    if (accepted) {
      await syncVault();
      await loadItems();
      const folderId = manifestId.toLowerCase();
      handleFolderClick({ Id: folderId, ManifestId: folderId });
    }
    await shared.reload();
  }, [syncVault, loadItems, handleFolderClick, shared]);

  /**
   * Create a new folder.
   */
  const handleCreateFolder = useCallback(async (folderName: string) => {
    await executeVaultMutation(async () => {
      await dbContext.sqliteClient!.folders.create(folderName, null);
    });
    await loadItems();
  }, [dbContext.sqliteClient, executeVaultMutation, loadItems]);

  /**
   * Handle item type selection from the FAB menu - navigate to the add item screen.
   * If there's a search query, pass it as itemUrl (if URL) or itemName (if not).
   */
  const handleAddItem = useCallback((itemType: ItemType) => {
    navigate(() => {
      const trimmedQuery = searchQuery.trim();
      if (trimmedQuery) {
        const isUrl = /^https?:\/\//i.test(trimmedQuery);
        const queryParam = isUrl ? 'itemUrl' : 'itemName';
        router.push(`/(tabs)/items/add?itemType=${itemType}&${queryParam}=${encodeURIComponent(trimmedQuery)}`);
      } else {
        router.push(`/(tabs)/items/add?itemType=${itemType}`);
      }
      HapticsUtility.impact();
    });
  }, [router, searchQuery, navigate]);

  const styles = StyleSheet.create({
    container: {
      paddingHorizontal: 0,
    },
    stepContainer: {
      flex: 1,
      gap: 8,
    },
    contentContainer: {
      paddingBottom: Platform.OS === 'ios' ? insets.bottom + 60 : 10,
      paddingHorizontal: 14,
      paddingTop: Platform.OS === 'ios' ? 42 : 8,
    },
    // Header row styles
    headerRow: {
      alignItems: 'center',
      flexDirection: 'row',
      justifyContent: 'space-between',
      marginBottom: 16,
    },
    // Filter button styles
    filterButton: {
      alignItems: 'center',
      flexDirection: 'row',
      flex: 1,
      gap: 8,
    },
    sortButton: {
      padding: 8,
    },
    filterButtonText: {
      color: colors.text,
      fontSize: 28,
      fontWeight: 'bold',
      lineHeight: 34,
    },
    filterCount: {
      color: colors.textMuted,
      fontSize: 20,
      lineHeight: 28,
    },
    // Folder pills styles
    folderPillsContainer: {
      flexDirection: 'row',
      flexWrap: 'wrap',
      gap: 8,
      marginBottom: 16,
    },
    newFolderButton: {
      alignItems: 'center',
      backgroundColor: colors.accentBackground,
      borderColor: colors.accentBorder,
      borderRadius: 20,
      borderStyle: 'dashed',
      borderWidth: 1,
      flexDirection: 'row',
      gap: 6,
      paddingHorizontal: 12,
      paddingVertical: 8,
    },
    newFolderButtonText: {
      color: colors.textMuted,
      fontSize: 14,
    },
    invitationPill: {
      alignItems: 'center',
      backgroundColor: colors.primary + '10',
      borderColor: colors.primary,
      borderRadius: 20,
      borderStyle: 'dashed',
      borderWidth: 1,
      flexDirection: 'row',
      gap: 6,
      paddingHorizontal: 12,
      paddingVertical: 8,
    },
    invitationPillLabel: {
      color: colors.primary,
      fontSize: 12,
    },
    invitationPillName: {
      color: colors.textMuted,
      fontSize: 14,
      maxWidth: 120,
    },
    // Search styles
    searchContainer: {
      position: 'relative',
      marginTop: 12,
    },
    searchIcon: {
      left: 12,
      position: 'absolute',
      top: 11,
      zIndex: 1,
    },
    searchInput: {
      backgroundColor: colors.accentBackground,
      borderRadius: 8,
      color: colors.text,
      fontSize: 16,
      height: 40,
      lineHeight: 20,
      marginBottom: 16,
      paddingLeft: 40,
      paddingRight: Platform.OS === 'android' ? 40 : 12,
    },
    clearButton: {
      padding: 4,
      position: 'absolute',
      right: 8,
      top: 4,
    },
    clearButtonText: {
      color: colors.textMuted,
      fontSize: 20,
    },
    // Empty state styles
    emptyContainer: {
      alignItems: 'center',
      marginTop: 24,
    },
    emptyText: {
      color: colors.textMuted,
      fontSize: 16,
      opacity: 0.7,
      textAlign: 'center',
    },
    clearButtonsContainer: {
      flexDirection: 'row',
      flexWrap: 'wrap',
      gap: 8,
      justifyContent: 'center',
      marginTop: 16,
    },
    clearSearchButton: {
      alignItems: 'center',
      backgroundColor: colors.accentBackground,
      borderRadius: 8,
      flexDirection: 'row',
      gap: 6,
      paddingHorizontal: 12,
      paddingVertical: 8,
    },
    clearSearchButtonText: {
      color: colors.text,
      fontSize: 14,
    },
    clearFilterButton: {
      alignItems: 'center',
      backgroundColor: colors.primary + '20',
      borderRadius: 8,
      flexDirection: 'row',
      gap: 6,
      paddingHorizontal: 12,
      paddingVertical: 8,
    },
    clearFilterButtonText: {
      color: colors.primary,
      fontSize: 14,
    },
    // Footer clear buttons styles (at bottom of list)
    footerClearContainer: {
      alignItems: 'center',
      flexDirection: 'row',
      flexWrap: 'wrap',
      gap: 8,
      justifyContent: 'center',
      marginTop: 16,
      paddingTop: 16,
    },
  });

  /**
   * Render the list header with filter button, folders, and search.
   */
  const renderListHeader = (): React.ReactNode => {
    return (
      <ThemedView>
        {/* Large header with logo (iOS only) */}
        {Platform.OS === 'ios' && (
          <View style={styles.headerRow}>
            <TouchableOpacity
              style={styles.filterButton}
              onPress={() => setShowFilterMenu(!showFilterMenu)}
            >
              <Logo width={40} height={40} />
              <ThemedText style={styles.filterButtonText}>
                {getFilterTitle()}
              </ThemedText>
              <ThemedText style={styles.filterCount}>
                ({filteredItems.length})
              </ThemedText>
              <MaterialIcons
                name={showFilterMenu ? "keyboard-arrow-up" : "keyboard-arrow-down"}
                size={28}
                color={colors.text}
              />
            </TouchableOpacity>
            {/* Sort button */}
            <TouchableOpacity
              style={styles.sortButton}
              onPress={() => setShowSortMenu(!showSortMenu)}
            >
              <MaterialIcons
                name="sort"
                size={24}
                color={colors.textMuted}
              />
            </TouchableOpacity>
          </View>
        )}

        {/* Search input */}
        <ThemedView style={styles.searchContainer}>
          <MaterialIcons
            name="search"
            size={20}
            color={colors.textMuted}
            style={styles.searchIcon}
          />
          <TextInput
            style={styles.searchInput}
            placeholder={t('items.searchPlaceholder')}
            placeholderTextColor={colors.textMuted}
            value={searchQuery}
            autoCorrect={false}
            autoCapitalize="none"
            multiline={false}
            numberOfLines={1}
            onChangeText={setSearchQuery}
            clearButtonMode={Platform.OS === 'ios' ? 'while-editing' : 'never'}
            testID="search-input"
          />
          {Platform.OS === 'android' && searchQuery.length > 0 && (
            <TouchableOpacity
              style={styles.clearButton}
              onPress={() => setSearchQuery('')}
              testID="clear-search-button"
            >
              <ThemedText style={styles.clearButtonText}>×</ThemedText>
            </TouchableOpacity>
          )}
        </ThemedView>

        {/* Folder pills (shown below search when not searching and showing folder items) */}
        {!searchQuery && showFolderItems && (
          <View style={styles.folderPillsContainer}>
            {foldersWithCounts.map((folder) => (
              <FolderPill
                key={scopedKey(folder.manifestId, folder.id)}
                folder={folder}
                onPress={() => handleFolderClick({ Id: folder.id, ManifestId: folder.manifestId })}
              />
            ))}
            {/* Invitations to shared folders wait in the folder list until they are answered. */}
            {shared.invitations.map(invitation => (
              <TouchableOpacity key={invitation.id} style={styles.invitationPill} onPress={() => setOpenInvitationId(invitation.id)} activeOpacity={0.7}>
                <MaterialIcons name="mail-outline" size={16} color={colors.primary} />
                <Text style={styles.invitationPillName} numberOfLines={1} ellipsizeMode="tail">{shared.invitationNames[invitation.id] ?? sharingText.sharedVault}</Text>
                <Text style={styles.invitationPillLabel}>{sharingText.invitationPending}</Text>
              </TouchableOpacity>
            ))}
            <TouchableOpacity
              style={styles.newFolderButton}
              onPress={() => setShowFolderModal(true)}
            >
              <MaterialIcons name="create-new-folder" size={16} color={colors.textMuted} />
              <Text style={styles.newFolderButtonText}>{t('items.folders.newFolder')}</Text>
            </TouchableOpacity>
          </View>
        )}
      </ThemedView>
    );
  };

  /**
   * Render empty state.
   */
  const renderEmptyComponent = (): React.ReactNode => {
    if (isLoadingItems) {
      return null;
    }

    /**
     * Determine the appropriate message based on search and filter state.
     */
    const getMessage = (): string => {
      // Both search and filter active
      if (searchQuery && filterType !== ItemFilter.All) {
        return t('items.noMatchingItemsWithFilter', { filter: getFilterTitle(), search: searchQuery });
      }
      // Only search active
      if (searchQuery) {
        return t('items.noMatchingItemsSearch', { search: searchQuery });
      }
      // Only filter active (no search)
      if (filterType !== ItemFilter.All) {
        return t('items.noMatchingItems');
      }
      // All items are in folders - show helpful message
      if (hasItemsInFoldersOnly) {
        return t('items.allItemsInFolders');
      }
      // No search, no filter - truly empty vault
      return t('items.noItemsFound');
    };

    const showClearButtons = searchQuery || filterType !== ItemFilter.All;

    return (
      <View style={styles.emptyContainer}>
        <Text style={styles.emptyText}>{getMessage()}</Text>

        {/* Clear search/filter buttons */}
        {showClearButtons && (
          <View style={styles.clearButtonsContainer}>
            {searchQuery && (
              <TouchableOpacity
                style={styles.clearSearchButton}
                onPress={() => setSearchQuery('')}
              >
                <MaterialIcons name="close" size={16} color={colors.text} />
                <Text style={styles.clearSearchButtonText}>{t('items.clearSearch')}</Text>
              </TouchableOpacity>
            )}
            {filterType !== ItemFilter.All && (
              <TouchableOpacity
                style={styles.clearFilterButton}
                onPress={() => setFilterType(ItemFilter.All)}
              >
                <MaterialIcons name="close" size={16} color={colors.primary} />
                <Text style={styles.clearFilterButtonText}>{t('items.clearFilter')}</Text>
              </TouchableOpacity>
            )}
          </View>
        )}
      </View>
    );
  };

  /**
   * Render list footer with clear filter/search buttons.
   * Only shown when there are items and a filter or search is active.
   */
  const renderListFooter = (): React.ReactNode => {
    // Don't show footer if loading, no items, or no active filter/search
    if (isLoadingItems || filteredItems.length === 0 || (filterType === ItemFilter.All && !searchQuery)) {
      return null;
    }

    return (
      <View style={styles.footerClearContainer}>
        {searchQuery && (
          <TouchableOpacity
            style={styles.clearSearchButton}
            onPress={() => setSearchQuery('')}
          >
            <MaterialIcons name="close" size={16} color={colors.text} />
            <Text style={styles.clearSearchButtonText}>{t('items.clearSearch')}</Text>
          </TouchableOpacity>
        )}
        {filterType !== ItemFilter.All && (
          <TouchableOpacity
            style={styles.clearFilterButton}
            onPress={() => setFilterType(ItemFilter.All)}
          >
            <MaterialIcons name="close" size={16} color={colors.primary} />
            <Text style={styles.clearFilterButtonText}>{t('items.clearFilter')}</Text>
          </TouchableOpacity>
        )}
      </View>
    );
  };

  return (
    <ThemedContainer style={styles.container} testID="items-screen">
      <CollapsibleHeader
        title={getFilterTitle()}
        scrollY={scrollY}
        showNavigationHeader={true}
        alwaysVisible={true}
      />
      <ThemedView style={styles.stepContainer}>
        {/* Item list */}
        <Animated.FlatList
          ref={flatListRef}
          testID="items-list"
          data={isLoadingItems ? Array(4).fill(null) : sortedItems}
          keyExtractor={(itm, index) => itm ? scopedKey(itm.ManifestId, itm.Id) : `skeleton-${index}`}
          keyboardShouldPersistTaps='handled'
          onScroll={Animated.event(
            [{ nativeEvent: { contentOffset: { y: scrollY } } }],
            { useNativeDriver: true }
          )}
          scrollEventThrottle={16}
          contentContainerStyle={styles.contentContainer}
          scrollIndicatorInsets={{ bottom: 40 }}
          initialNumToRender={14}
          maxToRenderPerBatch={14}
          windowSize={7}
          removeClippedSubviews={false}
          ListHeaderComponent={renderListHeader() as React.ReactElement}
          onScrollToIndexFailed={({ index, averageItemLength }) => {
            flatListRef.current?.scrollToOffset({ offset: index * averageItemLength, animated: true });
          }}
          refreshControl={
            <RefreshControl
              refreshing={refreshing}
              onRefresh={onRefresh}
              colors={[colors.primary]}
              tintColor={colors.primary}
            />
          }
          renderItem={({ item: itm }) =>
            isLoadingItems ? (
              <SkeletonLoader count={1} height={60} parts={2} />
            ) : (
              <ItemCard item={itm} onItemDelete={onItemDelete} onItemDuplicate={onItemDuplicate} showFolderPath={!!searchQuery} isHighlighted={scopedKey(itm.ManifestId, itm.Id) === highlightedItemKey} />
            )
          }
          ListEmptyComponent={renderEmptyComponent() as React.ReactElement}
          ListFooterComponent={renderListFooter() as React.ReactElement}
        />
      </ThemedView>

      {/* FAB with item type menu */}
      <AddItemFab onSelectType={handleAddItem} testID="add-item-button" />

      {/* Filter menu overlay */}
      <ItemFilterMenu
        visible={showFilterMenu}
        activeFilter={filterType}
        recentlyDeletedCount={recentlyDeletedCount}
        showFoldersToggle
        showFolders={showFolderItems}
        onClose={() => setShowFilterMenu(false)}
        onSelectFilter={(filter) => setFilterType(filter)}
        onSelectRecentlyDeleted={() => router.push('/(tabs)/items/deleted')}
        onToggleShowFolders={(next) => {
          setShowFolderItems(next);
          LocalPreferencesService.setShowFolders(next);
        }}
      />

      {/* Sort menu overlay */}
      <SortMenu
        visible={showSortMenu}
        sortOrder={sortOrder}
        onSelect={async (order: CredentialSortOrder) => {
          setSortOrder(order);
          // Save to settings and trigger vault sync
          await executeVaultMutation(async () => {
            await dbContext.sqliteClient?.settings.setCredentialsSortOrder(order);
          });
        }}
        onClose={() => setShowSortMenu(false)}
      />

      {/* Create folder modal */}
      <FolderModal
        isOpen={showFolderModal}
        onClose={() => setShowFolderModal(false)}
        onSave={handleCreateFolder}
        mode="create"
      />

      {((): React.ReactNode => {
        const invitation = shared.invitations.find(candidate => candidate.id === openInvitationId) ?? null;
        return (
          <SharedFolderInvitationModal
            invitation={invitation}
            folderName={invitation ? shared.invitationNames[invitation.id] ?? sharingText.sharedVault : ''}
            onDone={accepted => (invitation ? finishInvitation(invitation.manifestId, accepted) : Promise.resolve())}
            onClose={() => setOpenInvitationId(null)}
          />
        );
      })()}
    </ThemedContainer>
  );
}