// Store state management - localStorage wrappers

const STORE_KEYS = {
  FAVORITES: 'sportzx_favorites',
  SETTINGS: 'sportzx_settings'
};

const DEFAULT_SETTINGS = {
  forceLowQuality: false,
  playerRender: 'Default',
  defaultServer: 'Primary Server',
  themeAccent: 'purple',
  channelsLayout: 'grid'
};

export const Store = {
  // --- FAVORITES MANAGEMENT ---
  getFavorites() {
    try {
      const favs = localStorage.getItem(STORE_KEYS.FAVORITES);
      return favs ? JSON.parse(favs) : [];
    } catch {
      return [];
    }
  },

  isFavorite(channelId) {
    const favorites = this.getFavorites();
    return favorites.includes(Number(channelId));
  },

  toggleFavorite(channelId) {
    const id = Number(channelId);
    let favorites = this.getFavorites();
    if (favorites.includes(id)) {
      favorites = favorites.filter(favId => favId !== id);
    } else {
      favorites.push(id);
    }
    localStorage.setItem(STORE_KEYS.FAVORITES, JSON.stringify(favorites));
    return favorites;
  },

  // --- SETTINGS MANAGEMENT ---
  getSettings() {
    try {
      const settings = localStorage.getItem(STORE_KEYS.SETTINGS);
      return settings ? { ...DEFAULT_SETTINGS, ...JSON.parse(settings) } : DEFAULT_SETTINGS;
    } catch {
      return DEFAULT_SETTINGS;
    }
  },

  getSetting(key) {
    const settings = this.getSettings();
    return settings[key] !== undefined ? settings[key] : DEFAULT_SETTINGS[key];
  },

  updateSetting(key, value) {
    const settings = this.getSettings();
    settings[key] = value;
    localStorage.setItem(STORE_KEYS.SETTINGS, JSON.stringify(settings));
    return settings;
  }
};
