const LS_KEY = 'fx_recent_currencies';
const MAX_RECENT = 8;
const CODE_RE = /^[A-Z]{3}$/;

function isValidCode(c: unknown): c is string {
  return typeof c === 'string' && CODE_RE.test(c);
}

export function getRecentCurrencies(): string[] {
  try {
    const raw = localStorage.getItem(LS_KEY);
    if (!raw) return [];
    const arr = JSON.parse(raw);
    if (!Array.isArray(arr)) return [];
    const valid = arr.filter(isValidCode);
    /* Deduplicate in case of stale data */
    return [...new Set(valid)];
  } catch {
    return [];
  }
}

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