All files / src/viewmodels/favorites useFavoriteLocationsViewModel.ts

79.21% Statements 141/178
50% Branches 36/72
92.3% Functions 24/26
80.12% Lines 133/166

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 3721x 1x     1x 1x 1x           1x   1x                                                         12x 17x           17x 17x               1x       1x       1x       1x 1x                                                   1x 37x   37x 37x 37x 37x 37x 37x 37x 37x 37x   37x 37x 37x 37x   37x   37x 20x           37x 8x 8x 8x 8x 8x 8x 8x     37x   37x 1x         1x 1x     37x   11x 1x 1x 1x 1x 1x     10x 10x   10x   10x 10x 9x   1x 1x     1x   10x 10x           37x 11x     37x 11x     37x 6x   5x 5x     37x 1x 1x     37x 4x 4x     37x 1x 1x 1x   1x   1x           1x 1x 1x 1x 1x         1x 1x         37x 3x 3x 3x 3x     37x 5x   5x   5x 1x 1x     4x 1x 1x     3x         3x         3x 3x   3x 3x                   2x 2x   2x 2x 2x   1x       1x 1x           1x   3x                       37x 1x         1x   1x 1x   1x 1x 1x                             1x       37x       37x                                                  
import { useCallback, useEffect, useRef, useState } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { FavoriteLocation } from '@/models/favorite';
import { LocationSuggestion } from '@/models/event';
import { ApiError } from '@/services/api';
import { searchLocation } from '@/services/eventService';
import {
  createFavoriteLocation,
  deleteFavoriteLocation,
  listFavoriteLocations,
} from '@/services/favoriteService';
 
const MAX_FAVORITE_LOCATIONS = 3;
const FAVORITE_LOCATIONS_LIMIT_MESSAGE =
  `You can save up to ${MAX_FAVORITE_LOCATIONS} favorite locations.`;
 
export interface FavoriteLocationsViewModel {
  locations: FavoriteLocation[];
  isLoading: boolean;
  isRefreshing: boolean;
  apiError: string | null;
  isAddModalOpen: boolean;
  addName: string;
  addLocationQuery: string;
  addSuggestions: LocationSuggestion[];
  isSearchingSuggestions: boolean;
  selectedSuggestion: LocationSuggestion | null;
  addError: string | null;
  isSubmittingAdd: boolean;
  removingLocationId: string | null;
  canAddMore: boolean;
 
  refresh: () => Promise<void>;
  openAddModal: () => void;
  closeAddModal: () => void;
  setAddName: (value: string) => void;
  setAddLocationQuery: (value: string) => void;
  selectSuggestion: (suggestion: LocationSuggestion) => void;
  submitAdd: () => Promise<void>;
  removeLocation: (id: string) => Promise<void>;
}
 
function sortFavoriteLocations(locations: FavoriteLocation[]): FavoriteLocation[] {
  return [...locations].sort((left, right) => {
    const nameComparison = left.name.localeCompare(
      right.name,
      undefined,
      { sensitivity: 'base' },
    );
 
    Eif (nameComparison !== 0) {
      return nameComparison;
    }
 
    return left.id.localeCompare(right.id);
  });
}
 
function getLoadErrorMessage(error: unknown): string {
  Iif (error instanceof ApiError && error.status === 401) {
    return 'You must be logged in to view favorite locations.';
  }
 
  Iif (error instanceof ApiError) {
    return error.message;
  }
 
  return 'Failed to load favorite locations. Please try again.';
}
 
function getCreateErrorMessage(error: unknown): string {
  Eif (error instanceof ApiError && error.code === 'favorite_location_limit_exceeded') {
    return FAVORITE_LOCATIONS_LIMIT_MESSAGE;
  }
 
  if (error instanceof ApiError && error.status === 401) {
    return 'You must be logged in to save favorite locations.';
  }
 
  if (error instanceof ApiError) {
    return error.message;
  }
 
  return 'Failed to save favorite location. Please try again.';
}
 
function getDeleteErrorMessage(error: unknown): string {
  if (error instanceof ApiError && error.status === 401) {
    return 'You must be logged in to manage favorite locations.';
  }
 
  if (error instanceof ApiError) {
    return error.message;
  }
 
  return 'Failed to remove favorite location. Please try again.';
}
 
export function useFavoriteLocationsViewModel(): FavoriteLocationsViewModel {
  const { token } = useAuth();
 
  const [locations, setLocations] = useState<FavoriteLocation[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [apiError, setApiError] = useState<string | null>(null);
  const [isAddModalOpen, setIsAddModalOpen] = useState(false);
  const [addName, setAddName] = useState('');
  const [addLocationQuery, setAddLocationQuery] = useState('');
  const [addSuggestions, setAddSuggestions] = useState<LocationSuggestion[]>([]);
  const [isSearchingSuggestions, setIsSearchingSuggestions] = useState(false);
  const [selectedSuggestion, setSelectedSuggestion] =
    useState<LocationSuggestion | null>(null);
  const [addError, setAddError] = useState<string | null>(null);
  const [isSubmittingAdd, setIsSubmittingAdd] = useState(false);
  const [removingLocationId, setRemovingLocationId] = useState<string | null>(null);
 
  const searchTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
 
  const clearPendingSearch = useCallback(() => {
    Eif (!searchTimeoutRef.current) return;
 
    clearTimeout(searchTimeoutRef.current);
    searchTimeoutRef.current = null;
  }, []);
 
  const resetAddForm = useCallback(() => {
    setAddName('');
    setAddLocationQuery('');
    setAddSuggestions([]);
    setSelectedSuggestion(null);
    setAddError(null);
    setIsSearchingSuggestions(false);
    clearPendingSearch();
  }, [clearPendingSearch]);
 
  const canAddMore = Boolean(token) && locations.length < MAX_FAVORITE_LOCATIONS;
 
  const syncLocations = useCallback(async () => {
    Iif (!token) {
      setLocations([]);
      return;
    }
 
    const response = await listFavoriteLocations(token);
    setLocations(sortFavoriteLocations(response.items));
  }, [token]);
 
  const fetchLocations = useCallback(
    async (mode: 'initial' | 'refresh') => {
      if (!token) {
        setLocations([]);
        setApiError('You must be logged in to view favorite locations.');
        setIsLoading(false);
        setIsRefreshing(false);
        return;
      }
 
      Eif (mode === 'initial') setIsLoading(true);
      Iif (mode === 'refresh') setIsRefreshing(true);
 
      setApiError(null);
 
      try {
        const response = await listFavoriteLocations(token);
        setLocations(sortFavoriteLocations(response.items));
      } catch (error) {
        Eif (mode === 'initial') {
          setLocations([]);
        }
 
        setApiError(getLoadErrorMessage(error));
      } finally {
        Eif (mode === 'initial') setIsLoading(false);
        Iif (mode === 'refresh') setIsRefreshing(false);
      }
    },
    [token],
  );
 
  useEffect(() => {
    void fetchLocations('initial');
  }, [fetchLocations]);
 
  useEffect(() => () => {
    clearPendingSearch();
  }, [clearPendingSearch]);
 
  const openAddModal = useCallback(() => {
    if (!token || !canAddMore) return;
 
    resetAddForm();
    setIsAddModalOpen(true);
  }, [canAddMore, resetAddForm, token]);
 
  const closeAddModal = useCallback(() => {
    setIsAddModalOpen(false);
    resetAddForm();
  }, [resetAddForm]);
 
  const handleSetAddName = useCallback((value: string) => {
    setAddName(value);
    setAddError(null);
  }, []);
 
  const handleSetAddLocationQuery = useCallback((value: string) => {
    setAddLocationQuery(value);
    setSelectedSuggestion(null);
    setAddError(null);
 
    clearPendingSearch();
 
    Iif (value.trim().length < 2) {
      setAddSuggestions([]);
      setIsSearchingSuggestions(false);
      return;
    }
 
    searchTimeoutRef.current = setTimeout(async () => {
      setIsSearchingSuggestions(true);
      try {
        const results = await searchLocation(value);
        setAddSuggestions(results);
      } catch {
        setAddSuggestions([]);
        setAddError('Failed to search locations. Please try again.');
      } finally {
        setIsSearchingSuggestions(false);
        searchTimeoutRef.current = null;
      }
    }, 300);
  }, [clearPendingSearch]);
 
  const selectSuggestion = useCallback((suggestion: LocationSuggestion) => {
    setSelectedSuggestion(suggestion);
    setAddLocationQuery(suggestion.display_name);
    setAddSuggestions([]);
    setAddError(null);
  }, []);
 
  const submitAdd = useCallback(async () => {
    Iif (isSubmittingAdd) return;
 
    const trimmedName = addName.trim();
 
    if (!trimmedName) {
      setAddError('Please enter a name for this location.');
      return;
    }
 
    if (!selectedSuggestion) {
      setAddError('Please search and select a location.');
      return;
    }
 
    Iif (!token) {
      setAddError('You must be logged in to save favorite locations.');
      return;
    }
 
    Iif (locations.length >= MAX_FAVORITE_LOCATIONS) {
      setAddError(FAVORITE_LOCATIONS_LIMIT_MESSAGE);
      return;
    }
 
    setIsSubmittingAdd(true);
    setAddError(null);
 
    try {
      const createdLocation = await createFavoriteLocation(
        {
          name: trimmedName,
          address: selectedSuggestion.display_name,
          lat: Number(selectedSuggestion.lat),
          lon: Number(selectedSuggestion.lon),
        },
        token,
      );
 
      setLocations((prev) =>
        sortFavoriteLocations([...prev, createdLocation]),
      );
      setApiError(null);
      setIsAddModalOpen(false);
      resetAddForm();
    } catch (error) {
      Eif (
        error instanceof ApiError
        && error.code === 'favorite_location_limit_exceeded'
      ) {
        try {
          await syncLocations();
        } catch {
          // Keep the user-visible mutation error; syncing is a best-effort fallback.
        }
      }
 
      setAddError(getCreateErrorMessage(error));
    } finally {
      setIsSubmittingAdd(false);
    }
  }, [
    addName,
    isSubmittingAdd,
    locations.length,
    resetAddForm,
    selectedSuggestion,
    syncLocations,
    token,
  ]);
 
  const removeLocation = useCallback(async (id: string) => {
    Iif (!token) {
      setApiError('You must be logged in to manage favorite locations.');
      return;
    }
 
    Iif (removingLocationId) return;
 
    setRemovingLocationId(id);
    setApiError(null);
 
    try {
      await deleteFavoriteLocation(id, token);
      setLocations((prev) => prev.filter((loc) => loc.id !== id));
    } catch (error) {
      if (
        error instanceof ApiError
        && error.code === 'favorite_location_not_found'
      ) {
        try {
          await syncLocations();
        } catch {
          // Preserve the primary mutation error if the follow-up sync also fails.
        }
      }
 
      setApiError(getDeleteErrorMessage(error));
    } finally {
      setRemovingLocationId((current) => (current === id ? null : current));
    }
  }, [removingLocationId, syncLocations, token]);
 
  const refresh = useCallback(async () => {
    await fetchLocations('refresh');
  }, [fetchLocations]);
 
  return {
    locations,
    isLoading,
    isRefreshing,
    apiError,
    isAddModalOpen,
    addName,
    addLocationQuery,
    addSuggestions,
    isSearchingSuggestions,
    selectedSuggestion,
    addError,
    isSubmittingAdd,
    removingLocationId,
    canAddMore,
    refresh,
    openAddModal,
    closeAddModal,
    setAddName: handleSetAddName,
    setAddLocationQuery: handleSetAddLocationQuery,
    selectSuggestion,
    submitAdd,
    removeLocation,
  };
}