export type ThemeMode = 'LIGHT' | 'DARK' | 'AUTO';

/**
 * Per browser/device key (no userId): the theme persists across sessions and
 * communities, so it can't be namespaced by user.
 */
export const THEME_MODE_STORAGE_KEY = 'hu_theme_mode';

/** Amplitude-facing value for the theme preference. */
export type AnalyticsThemeMode = 'light' | 'dark' | 'system';

/** Reads the persisted theme mode from localStorage, defaulting to AUTO. */
export const readStoredThemeMode = (): ThemeMode => {
  try {
    const stored = localStorage.getItem(THEME_MODE_STORAGE_KEY);
    if (!stored) return 'AUTO';
    const parsed: unknown = JSON.parse(stored);
    if (parsed === 'LIGHT' || parsed === 'DARK' || parsed === 'AUTO') {
      return parsed;
    }
    return 'AUTO';
  } catch {
    return 'AUTO';
  }
};

/** Maps the internal mode to the Amplitude-facing value (AUTO → system). */
export const toAnalyticsThemeMode = (mode: ThemeMode): AnalyticsThemeMode => {
  if (mode === 'LIGHT') return 'light';
  if (mode === 'DARK') return 'dark';
  return 'system';
};

/** Returns the stored theme mode mapped to its Amplitude-facing value. */
export const readPreferredAnalyticsMode = (): AnalyticsThemeMode =>
  toAnalyticsThemeMode(readStoredThemeMode());
