const LS_KEY = 'fx_recent_currencies';
const MAX_RECENT = 8;

export function getRecentCurrencies(): string[] {
  try {
    const raw = localStorage.getItem(LS_KEY);
    if (!raw) return [];
    const arr = JSON.parse(raw);
    return Array.isArray(arr) ? arr.filter((c: unknown) => typeof c === 'string') : [];
  } catch {
    return [];
  }
}

export function addRecentCurrency(code: string): void {
  try {
    const list = getRecentCurrencies().filter((c) => c !== code);
    list.unshift(code);
    localStorage.setItem(LS_KEY, JSON.stringify(list.slice(0, MAX_RECENT)));
  } catch {
    /* Private browsing — silently ignore */
  }
}
