/**
 * localStorage-backed persistence for the editor.
 *
 * Persists across reloads:
 *   - The current design (elements + active template id)
 *   - User preferences (last shirt color, last shirt size, last font)
 *   - Recent picks (recent colors, recent fonts)
 *
 * Doesn't persist:
 *   - Selection (transient)
 *   - Mobile sheet open/closed (transient)
 *   - Undo history (would balloon storage; user gets a fresh history on
 *     reload, which is the standard expectation)
 *   - Element images whose `src` is a `blob:` URL (those URLs become
 *     invalid the moment the tab refreshes, so saving them just produces
 *     broken images on restore). Image elements with `data:` URLs or
 *     remote URLs are kept.
 *
 * Single key, single JSON blob — keeps reads/writes atomic and the
 * implementation small. The `version` field lets us migrate the schema
 * later (or just bail out cleanly when we encounter old data).
 *
 * Storage details (SSR guard, JSON parsing, quota errors) live in
 * `utils/storage.js` so other persistence-shaped consumers can reuse the
 * same wrapper without re-deriving the safety net.
 */

import { readJson, writeJson, removeKey } from './storage';
import { isBlobUrl } from './blobUrl';

const STORAGE_KEY = 'pawfectly-yours-state-v1';

/**
 * Load whatever was last persisted. Returns `null` if storage isn't
 * available, the key isn't set, or the stored data is malformed —
 * callers should treat any of these the same as "fresh start".
 */
export function loadPersistedState() {
  const parsed = readJson(STORAGE_KEY);
  if (!parsed || typeof parsed !== 'object') return null;
  return parsed;
}

/**
 * Persist the given state, after stripping anything we know won't
 * round-trip cleanly (notably blob: URLs from photo uploads).
 *
 * Silent no-op on errors: storage may be full, disabled (Safari private
 * mode), or otherwise unavailable. We never want a save attempt to
 * crash the app, so failures are swallowed inside `writeJson`.
 */
export function savePersistedState(state) {
  writeJson(STORAGE_KEY, stripUnpersistable(state));
}

/**
 * Wipe persisted state. Used by the "Clear canvas" action when the user
 * wants a fresh start that survives a reload.
 */
export function clearPersistedState() {
  removeKey(STORAGE_KEY);
}

function stripUnpersistable(state) {
  if (!state || typeof state !== 'object') return state;
  const out = { ...state };
  if (Array.isArray(out.elements)) {
    out.elements = out.elements.filter((el) => {
      // blob: URLs go stale immediately on reload; persisting them
      // produces broken-image elements that the user has to manually
      // delete. data: and remote URLs survive a reload, so those stay.
      // Filtering on the URL prefix (rather than the element type) means
      // any future element type that ends up holding a blob URL gets the
      // same treatment automatically.
      if (el && isBlobUrl(el.src)) return false;
      return true;
    });
  }
  return out;
}
