/**
 * localStorage utility for tracking recently visited flows.
 */

const STORAGE_KEY = 'rf_recent_flows'
const MAX_ENTRIES = 10

export interface RecentFlow {
  id: string
  name: string
  tree_type: string
  timestamp: number
}

export function getRecentFlows(limit = 5): RecentFlow[] {
  try {
    const raw = localStorage.getItem(STORAGE_KEY)
    if (!raw) return []
    const parsed = JSON.parse(raw) as RecentFlow[]
    return Array.isArray(parsed) ? parsed.slice(0, limit) : []
  } catch {
    return []
  }
}

export function addRecentFlow(flow: Omit<RecentFlow, 'timestamp'>): void {
  try {
    const existing = getRecentFlows(MAX_ENTRIES)
    // Deduplicate by id — remove any existing entry with the same id
    const deduped = existing.filter(f => f.id !== flow.id)
    // Add to front with current timestamp
    const updated: RecentFlow[] = [
      { ...flow, timestamp: Date.now() },
      ...deduped,
    ].slice(0, MAX_ENTRIES)
    localStorage.setItem(STORAGE_KEY, JSON.stringify(updated))
  } catch {
    // Silently ignore localStorage errors (private browsing, quota exceeded)
  }
}
