// Local-only favorites and dietary goal (no cloud backend).
(function (global) {
  var FAV_KEY = 'fc_fav_slugs';
  var GOAL_KEY = 'fc_diet_goal';

  function readJson(key, fallback) {
    try {
      var raw = global.localStorage.getItem(key);
      if (!raw) return fallback;
      return JSON.parse(raw);
    } catch (e) {
      return fallback;
    }
  }

  function writeJson(key, value) {
    try {
      global.localStorage.setItem(key, JSON.stringify(value));
    } catch (e) {
      /* ignore quota errors */
    }
  }

  global.fcLocal = {
    getFavorites: function () {
      var list = readJson(FAV_KEY, []);
      return Array.isArray(list) ? list : [];
    },
    hasFavorite: function (slug) {
      return this.getFavorites().indexOf(slug) !== -1;
    },
    toggleFavorite: function (slug) {
      var list = this.getFavorites();
      var idx = list.indexOf(slug);
      if (idx === -1) {
        list.push(slug);
      } else {
        list.splice(idx, 1);
      }
      writeJson(FAV_KEY, list);
      return list;
    },
    getGoal: function () {
      try {
        return global.localStorage.getItem(GOAL_KEY) || '';
      } catch (e) {
        return '';
      }
    },
    setGoal: function (goal) {
      try {
        if (goal) {
          global.localStorage.setItem(GOAL_KEY, goal);
        } else {
          global.localStorage.removeItem(GOAL_KEY);
        }
      } catch (e) {
        /* ignore */
      }
    }
  };
})(window);
