const STORAGE_KEY = 'splint-recent-ledgers';
const MAX_ENTRIES = 20;

export interface RecentLedger {
  id: string;
  name: string;
}

export function getRecentLedgers(): RecentLedger[] {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return [];
    const parsed = JSON.parse(raw);
    if (!Array.isArray(parsed)) return [];
    return parsed.filter(
      (e): e is RecentLedger =>
        typeof e.id === 'string' &&
        typeof e.name === 'string',
    );
  } catch {
    return [];
  }
}

export function addRecentLedger(ledger: RecentLedger): void {
  const existing = getRecentLedgers();
  const filtered = existing.filter((e) => e.id !== ledger.id);
  const updated = [ledger, ...filtered].slice(0, MAX_ENTRIES);
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(updated));
  } catch {
    // localStorage may be full or unavailable — silently ignore
  }
}
