import { describe, it, expect, beforeEach, vi } from "vitest";
import { readTrendsChartType, TRENDS_CHART_TYPE_STORAGE_KEY } from "./TrendsChartTypeToggle";

describe("readTrendsChartType", () => {
  const store = new Map<string, string>();
  const mockLocalStorage = {
    getItem: vi.fn((key: string) => store.get(key) ?? null),
    setItem: vi.fn((key: string, value: string) => {
      store.set(key, value);
    }),
    removeItem: vi.fn((key: string) => {
      store.delete(key);
    }),
    clear: vi.fn(() => store.clear()),
    key: vi.fn(),
    length: 0,
  };

  beforeEach(() => {
    store.clear();
    vi.stubGlobal("localStorage", mockLocalStorage);
  });

  it("returns 'bar' fallback when key is missing", () => {
    expect(readTrendsChartType()).toBe("bar");
  });

  it("returns 'bar' when stored value is 'bar'", () => {
    store.set(TRENDS_CHART_TYPE_STORAGE_KEY, "bar");
    expect(readTrendsChartType()).toBe("bar");
  });

  it("migrates legacy 'line' stored value to 'bar'", () => {
    store.set(TRENDS_CHART_TYPE_STORAGE_KEY, "line");
    expect(readTrendsChartType()).toBe("bar");
  });

  it("returns 'area' when stored value is 'area'", () => {
    store.set(TRENDS_CHART_TYPE_STORAGE_KEY, "area");
    expect(readTrendsChartType()).toBe("area");
  });

  it("ignores invalid stored values and returns fallback", () => {
    store.set(TRENDS_CHART_TYPE_STORAGE_KEY, "bogus");
    expect(readTrendsChartType(TRENDS_CHART_TYPE_STORAGE_KEY, "area")).toBe("area");
  });

  it("respects custom fallback when provided", () => {
    expect(readTrendsChartType(TRENDS_CHART_TYPE_STORAGE_KEY, "area")).toBe("area");
  });

  it("uses the expected storage key", () => {
    expect(TRENDS_CHART_TYPE_STORAGE_KEY).toBe("reports-trends-category-charttype");
  });
});
