import type { LayoutPersistence, LayoutSpec } from './types.js';

/**
 * Default persistence layer — backed by `localStorage`. SSR-safe
 * (returns `null` / no-op when `window` is absent).
 *
 * Hosts on `platform-service` should pass their own `LayoutPersistence`
 * to `<Workspace>` that round-trips through the
 * `/api/platform/layouts/{routeKey}` endpoint.
 */
export const localStoragePersistence: LayoutPersistence = {
  save: (key, layout) => {
    if (typeof window === 'undefined') return;
    try {
      window.localStorage.setItem(key, JSON.stringify(layout));
    } catch {
      /* quota / disabled — silently ignore */
    }
  },
  load: (key) => {
    if (typeof window === 'undefined') return null;
    try {
      const raw = window.localStorage.getItem(key);
      if (!raw) return null;
      const parsed = JSON.parse(raw);
      if (parsed && Array.isArray(parsed.entries)) {
        return parsed as LayoutSpec;
      }
      return null;
    } catch {
      return null;
    }
  },
};
