import { describe, it, expect, beforeEach, afterEach } from "vitest";
import { setActivePinia, createPinia } from "pinia";
import { useFavoritesStore } from "../favorites.js";

describe("useFavoritesStore", () => {
  let storage = {};

  beforeEach(() => {
    storage = {};
    global.localStorage = {
      getItem: (key) => storage[key] ?? null,
      setItem: (key, value) => {
        storage[key] = value;
      },
    };
    setActivePinia(createPinia());
  });

  afterEach(() => {
    vi.restoreAllMocks();
  });

  it("reads existing favorites from localStorage", () => {
    storage["sh_fav_areas"] = '["1","3","5"]';
    const store = useFavoritesStore();

    expect(store.ids).toEqual(["1", "3", "5"]);
  });

  it("starts empty when localStorage is empty", () => {
    const store = useFavoritesStore();

    expect(store.ids).toEqual([]);
  });

  it("adds a favorite and persists to localStorage", () => {
    const store = useFavoritesStore();

    store.add(42);

    expect(store.has(42)).toBe(true);
    expect(storage["sh_fav_areas"]).toBe('["42"]');
  });

  it("does not duplicate favorites", () => {
    const store = useFavoritesStore();

    store.add(1);
    store.add(1);

    expect(store.ids).toEqual(["1"]);
  });

  it("removes a favorite and persists to localStorage", () => {
    const store = useFavoritesStore();

    store.add(1);
    store.add(2);
    store.remove(1);

    expect(store.has(1)).toBe(false);
    expect(store.has(2)).toBe(true);
    expect(storage["sh_fav_areas"]).toBe('["2"]');
  });

  it("toggle adds when not present", () => {
    const store = useFavoritesStore();

    const result = store.toggle(7);

    expect(result).toBe(true);
    expect(store.has(7)).toBe(true);
  });

  it("toggle removes when present", () => {
    const store = useFavoritesStore();

    store.add(7);
    const result = store.toggle(7);

    expect(result).toBe(false);
    expect(store.has(7)).toBe(false);
  });

  it("coerces ids to strings", () => {
    const store = useFavoritesStore();

    store.add(1);
    store.add("1");

    expect(store.ids).toEqual(["1"]);
  });

  it("handles invalid localStorage gracefully", () => {
    storage["sh_fav_areas"] = "not json";
    const store = useFavoritesStore();

    expect(store.ids).toEqual([]);
  });
});
