/**
 * LocalStorage utilities for persisting user data
 */

const FAVORITES_KEY = 'units-ui-favorites';

/**
 * Get favorite units
 */
export function getFavorites(): string[] {
  if (typeof window === 'undefined') return [];

  try {
    const stored = localStorage.getItem(FAVORITES_KEY);
    return stored ? JSON.parse(stored) : [];
  } catch {
    return [];
  }
}

/**
 * Add unit to favorites
 */
export function addToFavorites(unit: string): void {
  if (typeof window === 'undefined') return;

  const favorites = getFavorites();
  if (!favorites.includes(unit)) {
    favorites.push(unit);
    localStorage.setItem(FAVORITES_KEY, JSON.stringify(favorites));
  }
}

/**
 * Remove unit from favorites
 */
export function removeFromFavorites(unit: string): void {
  if (typeof window === 'undefined') return;

  const favorites = getFavorites();
  const filtered = favorites.filter(u => u !== unit);
  localStorage.setItem(FAVORITES_KEY, JSON.stringify(filtered));
}

/**
 * Toggle favorite status
 */
export function toggleFavorite(unit: string): boolean {
  const favorites = getFavorites();
  const isFavorite = favorites.includes(unit);

  if (isFavorite) {
    removeFromFavorites(unit);
    return false;
  } else {
    addToFavorites(unit);
    return true;
  }
}
