import { ref } from "vue";
import { defineStore } from "pinia";

const STORAGE_KEY = "sh_fav_areas";

function readFavorites() {
  try {
    return JSON.parse(localStorage.getItem(STORAGE_KEY) || "[]").map(String);
  } catch (_) {
    return [];
  }
}

function writeFavorites(ids) {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(ids.map(String)));
}

export const useFavoritesStore = defineStore("favorites", () => {
  const ids = ref(readFavorites());

  function has(id) {
    return ids.value.includes(String(id));
  }

  function add(id) {
    const nextId = String(id);
    if (!ids.value.includes(nextId)) {
      ids.value.push(nextId);
      writeFavorites(ids.value);
    }
  }

  function remove(id) {
    ids.value = ids.value.filter((item) => item !== String(id));
    writeFavorites(ids.value);
  }

  function toggle(id) {
    if (has(id)) {
      remove(id);
      return false;
    }
    add(id);
    return true;
  }

  return {
    ids,
    has,
    add,
    remove,
    toggle,
  };
});
