import type { AsukaExportedState } from './stateManager';

export type AsukaStorageOptions = {
  key?: string;
};

export function saveStateToStorage(state: AsukaExportedState, options: AsukaStorageOptions = {}): void {
  const key = options.key ?? 'asukaDesignerState';
  try {
    localStorage.setItem(key, JSON.stringify(state));
  } catch {
    // ignore quota / private mode errors
  }
}

export function loadStateFromStorage(options: AsukaStorageOptions = {}): AsukaExportedState | null {
  const key = options.key ?? 'asukaDesignerState';
  try {
    const raw = localStorage.getItem(key);
    if (!raw) return null;
    const parsed = JSON.parse(raw) as unknown;
    if (!parsed || typeof parsed !== 'object') return null;
    const state = parsed as Partial<AsukaExportedState>;
    if (state.format !== 'asuka-state' || state.schemaVersion !== 2) return null;
    return state as AsukaExportedState;
  } catch {
    return null;
  }
}

export function clearStateStorage(options: AsukaStorageOptions = {}): void {
  const key = options.key ?? 'asukaDesignerState';
  try {
    localStorage.removeItem(key);
  } catch {
    // ignore
  }
}
