// Portable grid-column preferences (visibility / order / width / sort).
//
// Stored in the DB settings table (so they travel with the logbook and
// survive a reinstall) AND mirrored to the WebView localStorage as a fast,
// flicker-free cache. On a fresh machine localStorage is empty, so we fall
// back to the DB copy and re-seed the cache.
import { GetUIPref, SetUIPref } from '../../wailsjs/go/main/App';

// loadLocal reads the cached column state synchronously (used in onGridReady
// to apply instantly, before the async DB round-trip).
export function loadLocal(key: string): any[] | null {
  try {
    const raw = localStorage.getItem(key);
    const v = raw ? JSON.parse(raw) : null;
    return Array.isArray(v) ? v : null;
  } catch {
    return null;
  }
}

// loadRemote pulls the portable copy from the DB (null if none / unset).
export async function loadRemote(key: string): Promise<any[] | null> {
  try {
    const v = await GetUIPref(key);
    const parsed = v ? JSON.parse(v) : null;
    return Array.isArray(parsed) ? parsed : null;
  } catch {
    return null;
  }
}

// saveState write-throughs to both the cache and the DB (fire-and-forget).
export function saveState(key: string, state: any[]) {
  const json = JSON.stringify(state);
  try { localStorage.setItem(key, json); } catch { /* quota / private mode */ }
  SetUIPref(key, json).catch(() => { /* DB unavailable — cache still holds it */ });
}

// seedLocal writes a value into the cache without touching the DB (used after
// hydrating the cache from the DB on a fresh machine).
export function seedLocal(key: string, state: any[]) {
  try { localStorage.setItem(key, JSON.stringify(state)); } catch { /* ignore */ }
}
