import { atomWithLocalStorage } from './utils/atomWithLocalStorage';

// Persisted across reloads and tabs as a plain string (not JSON-encoded)
// to stay backwards-compatible with the legacy `localStorage.setItem(key, roomId)`
// writes that shipped before this atom existed.
export const ACTIVE_CHANNELS_SPACE_KEY = 'vojo.activeSpaceId';

const getRawString = (key: string): string | undefined => {
  try {
    return localStorage.getItem(key) ?? undefined;
  } catch {
    return undefined;
  }
};

const setRawString = (key: string, value: string | undefined) => {
  try {
    if (value === undefined) {
      localStorage.removeItem(key);
    } else {
      localStorage.setItem(key, value);
    }
  } catch {
    /* private mode / quota — non-fatal */
  }
};

// Single source of truth for the channels-tab «active workspace» selection.
// Subscribed reads (via `useAtomValue`) re-render when the atom is written
// in the same tab and when another tab updates localStorage — fixes the
// stale-memo bug where `MobileTabsPager` cached the persisted value at
// first render and never refreshed after the user picked a new workspace.
export const activeChannelsSpaceAtom = atomWithLocalStorage<string | undefined>(
  ACTIVE_CHANNELS_SPACE_KEY,
  getRawString,
  setRawString
);
