'use client';

const FAVORITES_KEY = 'figlet-ui-favorites';
const RECENT_FONTS_KEY = 'figlet-ui-recent-fonts';
const MAX_RECENT = 10;

export function getFavorites(): string[] {
  if (typeof window === 'undefined') return [];

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

export function addFavorite(fontName: string): void {
  const favorites = getFavorites();
  if (!favorites.includes(fontName)) {
    favorites.push(fontName);
    localStorage.setItem(FAVORITES_KEY, JSON.stringify(favorites));
  }
}

export function removeFavorite(fontName: string): void {
  const favorites = getFavorites();
  const filtered = favorites.filter(f => f !== fontName);
  localStorage.setItem(FAVORITES_KEY, JSON.stringify(filtered));
}

export function isFavorite(fontName: string): boolean {
  return getFavorites().includes(fontName);
}

export function toggleFavorite(fontName: string): boolean {
  const isCurrentlyFavorite = isFavorite(fontName);
  if (isCurrentlyFavorite) {
    removeFavorite(fontName);
  } else {
    addFavorite(fontName);
  }
  return !isCurrentlyFavorite;
}

export function getRecentFonts(): string[] {
  if (typeof window === 'undefined') return [];

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

export function addRecentFont(fontName: string): void {
  let recent = getRecentFonts();

  // Remove if already exists
  recent = recent.filter(f => f !== fontName);

  // Add to beginning
  recent.unshift(fontName);

  // Keep only MAX_RECENT items
  recent = recent.slice(0, MAX_RECENT);

  localStorage.setItem(RECENT_FONTS_KEY, JSON.stringify(recent));
}
