/** * LocalStorage utilities for persisting user data */ export interface ConversionRecord { id: string; timestamp: number; from: { value: number; unit: string; }; to: { value: number; unit: string; }; measure: string; } const HISTORY_KEY = 'units-ui-history'; const FAVORITES_KEY = 'units-ui-favorites'; const MAX_HISTORY = 50; /** * Save conversion to history */ export function saveToHistory(record: Omit): void { if (typeof window === 'undefined') return; const history = getHistory(); const newRecord: ConversionRecord = { ...record, id: crypto.randomUUID(), timestamp: Date.now(), }; // Add to beginning and limit size const updated = [newRecord, ...history].slice(0, MAX_HISTORY); localStorage.setItem(HISTORY_KEY, JSON.stringify(updated)); } /** * Get conversion history */ export function getHistory(): ConversionRecord[] { if (typeof window === 'undefined') return []; try { const stored = localStorage.getItem(HISTORY_KEY); return stored ? JSON.parse(stored) : []; } catch { return []; } } /** * Clear conversion history */ export function clearHistory(): void { if (typeof window === 'undefined') return; localStorage.removeItem(HISTORY_KEY); } /** * Get favorite units */ export function getFavorites(): string[] { if (typeof window === 'undefined') return []; try { const stored = localStorage.getItem(FAVORITES_KEY); return stored ? JSON.parse(stored) : []; } catch { return []; } } /** * Add unit to favorites */ export function addToFavorites(unit: string): void { if (typeof window === 'undefined') return; const favorites = getFavorites(); if (!favorites.includes(unit)) { favorites.push(unit); localStorage.setItem(FAVORITES_KEY, JSON.stringify(favorites)); } } /** * Remove unit from favorites */ export function removeFromFavorites(unit: string): void { if (typeof window === 'undefined') return; const favorites = getFavorites(); const filtered = favorites.filter(u => u !== unit); localStorage.setItem(FAVORITES_KEY, JSON.stringify(filtered)); } /** * Toggle favorite status */ export function toggleFavorite(unit: string): boolean { const favorites = getFavorites(); const isFavorite = favorites.includes(unit); if (isFavorite) { removeFromFavorites(unit); return false; } else { addToFavorites(unit); return true; } }