/**
 * Safe localStorage wrapper.
 *
 * Before this module, `persistence.js` had three try/catch blocks each with
 * a separate `typeof window === 'undefined' || !window.localStorage` guard
 * — the same logic three times. Wrapping them once makes the persistence
 * code read like the actual save/load shape it expresses, not the
 * defensive coding around it.
 *
 * Failure modes we silently absorb:
 *   - SSR (no `window`)
 *   - Browser private mode where storage is disabled (Safari throws)
 *   - Quota exceeded (full storage)
 *   - JSON parse errors when reading back malformed values
 *
 * In all cases callers see `null` (for read) or false (for write) — never
 * an exception. Persistence shouldn't crash the app, ever.
 */

function hasStorage() {
  return typeof window !== 'undefined' && !!window.localStorage;
}

/**
 * Read and JSON-parse the value at `key`. Returns null when storage is
 * unavailable, the key is missing, or the stored value isn't valid JSON.
 */
export function readJson(key) {
  if (!hasStorage()) return null;
  try {
    const raw = window.localStorage.getItem(key);
    if (!raw) return null;
    return JSON.parse(raw);
  } catch {
    return null;
  }
}

/**
 * JSON-stringify and store `value` at `key`. Returns true on success,
 * false on any failure.
 */
export function writeJson(key, value) {
  if (!hasStorage()) return false;
  try {
    window.localStorage.setItem(key, JSON.stringify(value));
    return true;
  } catch {
    return false;
  }
}

/**
 * Delete `key`. Returns true on success, false on any failure.
 */
export function removeKey(key) {
  if (!hasStorage()) return false;
  try {
    window.localStorage.removeItem(key);
    return true;
  } catch {
    return false;
  }
}
