// ─── Safe Persist Storage ─────────────────────────────────────────────────────
// Wraps localStorage with error handling for Zustand persist middleware.
// Handles: quota exceeded, corrupted JSON, and unexpected read/write failures.

import type { StateStorage } from 'zustand/middleware';

/**
 * Creates a safe localStorage wrapper for Zustand persist.
 * - Corrupted JSON → returns null (Zustand uses initial state)
 * - Quota exceeded → logs warning, skips write
 * - Other errors → logs warning, graceful fallback
 */
export function createSafeStorage(): StateStorage {
  return {
    getItem: (name: string): unknown => {
      try {
        const str = localStorage.getItem(name);
        if (str === null) return null;
        return JSON.parse(str);
      } catch (error) {
        console.warn(`[persist] Failed to read "${name}" from localStorage:`, error);
        try {
          localStorage.removeItem(name);
        } catch {
          // ignore
        }
        return null;
      }
    },
    setItem: (name: string, value: unknown): void => {
      try {
        localStorage.setItem(name, JSON.stringify(value));
      } catch (error) {
        if (error instanceof DOMException && error.name === 'QuotaExceededError') {
          console.warn(`[persist] localStorage quota exceeded for "${name}". State will not persist this tick.`);
        } else {
          console.warn(`[persist] Failed to write "${name}" to localStorage:`, error);
        }
      }
    },
    removeItem: (name: string): void => {
      try {
        localStorage.removeItem(name);
      } catch (error) {
        console.warn(`[persist] Failed to remove "${name}" from localStorage:`, error);
      }
    },
  };
}
