type CacheEntry = { ts: number; value: any };
const MEM: Map<string, CacheEntry> = new Map();
const PREFIX = 'app_cache_v1:';

export function getCached<T>(key: string, maxAgeSec = 300): T | null {
  const mem = MEM.get(key);
  if (mem && (Date.now() - mem.ts) < maxAgeSec * 1000) return mem.value as T;
  try {
    const sess = sessionStorage.getItem(PREFIX + key);
    if (sess) {
      const parsed: CacheEntry = JSON.parse(sess);
      if ((Date.now() - parsed.ts) < maxAgeSec * 1000) {
        MEM.set(key, parsed);
        return parsed.value as T;
      }
    }
  } catch (e) {
    // ignore parse errors or storage errors
  }
  return null;
}

export function setCached<T>(key: string, value: T) {
  const entry: CacheEntry = { ts: Date.now(), value };
  MEM.set(key, entry);
  try { sessionStorage.setItem(PREFIX + key, JSON.stringify(entry)); } catch (e) { /* ignore */ }
}

export function clearCached(key: string) {
  MEM.delete(key);
  try { sessionStorage.removeItem(PREFIX + key); } catch (e) { /* ignore */ }
}
