/* Persistence — localStorage-backed React state.
   Bumping DATA_VERSION discards everything users saved under older versions
   (use it when the seed data shape in data.jsx changes incompatibly).
   The Settings → "Reset demo data" button is the manual escape hatch. */
const DATA_VERSION = 1;
const STORE_PREFIX = 'ghr:v' + DATA_VERSION + ':';
const LOCK_KEY = 'ghr:unlocked'; // deliberately outside the versioned prefix — survives data resets

/* one-time cleanup: drop keys from older data versions */
(function migrateStore() {
  try {
    const stale = [];
    for (let i = 0; i < localStorage.length; i++) {
      const k = localStorage.key(i);
      if (k && k.startsWith('ghr:v') && !k.startsWith(STORE_PREFIX)) stale.push(k);
    }
    stale.forEach((k) => localStorage.removeItem(k));
  } catch (e) {}
})();

/* useState that reads its initial value from localStorage and writes every change back */
function usePersistentState(key, initial) {
  const full = STORE_PREFIX + key;
  const [val, setVal] = React.useState(() => {
    try {
      const raw = localStorage.getItem(full);
      if (raw != null) return JSON.parse(raw);
    } catch (e) {}
    return typeof initial === 'function' ? initial() : initial;
  });
  React.useEffect(() => {
    try { localStorage.setItem(full, JSON.stringify(val)); } catch (e) {}
  }, [full, val]);
  return [val, setVal];
}

function clearPersistedData() {
  try {
    const mine = [];
    for (let i = 0; i < localStorage.length; i++) {
      const k = localStorage.key(i);
      if (k && k.startsWith(STORE_PREFIX)) mine.push(k);
    }
    mine.forEach((k) => localStorage.removeItem(k));
  } catch (e) {}
}

Object.assign(window, { DATA_VERSION, STORE_PREFIX, LOCK_KEY, usePersistentState, clearPersistedData });
