// Portable UI preferences.
//
// A handful of small UI prefs historically lived only in the WebView's
// localStorage, so they did NOT travel when the operator copied the OpsLog
// folder (data/) to another machine. These helpers mirror them into the DB
// settings table (ui.* keys, like the grid columns) so the whole setup is
// identical after a copy.
import { GetUIPref, SetUIPref } from '../../wailsjs/go/main/App';

// Keys that must travel with data/ (DB is the portable source of truth; the
// localStorage copy is just a fast, synchronous cache).
const PORTABLE_KEYS = [
  'opslog.theme',         // UI colour theme (light-warm / dark-warm / graphite / high-contrast / auto)
  'hamlog.qsoLimit',      // QSO list page size
  'bandmap.side',         // band map docked left / right
  'bandmap.show',         // band map open / closed
  'opslog.autofocusWB',   // auto-focus Worked-before
  'hamlog.filterPresets', // Filter Builder saved presets
  'opslog.showRotor',     // rotor compass shown next to the keyers
  'opslog.showBeamOnMap', // antenna beam lobe drawn on the Main map
  'opslog.startEqualsEnd',// log TIME_ON = TIME_OFF (QSO time = completion time)
  'opslog.showQsoRate',   // QSO-rate meter (10/60 min) shown in the header
  'opslog.catModeBeforeFreq', // send CAT mode before frequency (older rigs)
  'opslog.bandMapBands',  // bands shown side-by-side in the Band Map tab
  'opslog.mapAutoZoomDX', // Main map: auto-zoom to the DX (vs free pan/zoom)
  'opslog.mapView',       // Main map: remembered free-pan view (lat/lon/zoom)
  'opslog.lookupOnBlur',  // run the callsign lookup on blur instead of while typing
  'opslog.clusterShowFilters', // cluster filter sidebar shown (tab + Main pane)
  'opslog.mapBasemap',    // world map basemap (light / street / satellite)
  // Cluster filter selections — restored on reopen.
  'opslog.clusterFilterSource', 'opslog.clusterGroup', 'opslog.clusterBands',
  'opslog.clusterLockBand', 'opslog.clusterLockMode', 'opslog.clusterStatusFilter',
  'opslog.clusterModeFilter', 'opslog.clusterSearch', 'opslog.clusterHideWorked',
  'opslog.activeTab',     // last selected tab
  'hamlog.awardColsShown', // which award columns are shown in the QSO grid
];

// syncPortablePrefs reconciles the DB with the local cache at startup:
//   • DB has a value  → copy it into localStorage (a copied folder restores it);
//   • DB empty, local set → seed the DB from local (migrates the current value).
// Call it BEFORE the first render so the app's synchronous localStorage reads
// already see the portable values — no per-component hydration needed.
export async function syncPortablePrefs(): Promise<void> {
  await Promise.all(PORTABLE_KEYS.map(async (key) => {
    try {
      const db = await GetUIPref(key);
      const local = localStorage.getItem(key);
      if (db != null && db !== '') {
        if (db !== local) { try { localStorage.setItem(key, db); } catch { /* quota */ } }
      } else if (local != null && local !== '') {
        await SetUIPref(key, local);
      }
    } catch { /* backend not ready / no DB — keep whatever is in localStorage */ }
  }));
}

// writeUiPref write-throughs a value to the local cache AND the portable DB.
// Use it everywhere these keys are written instead of localStorage.setItem.
export function writeUiPref(key: string, value: string): void {
  try { localStorage.setItem(key, value); } catch { /* quota / private mode */ }
  SetUIPref(key, value).catch(() => { /* DB unavailable — the cache still holds it */ });
}
