import { describe, it, expect, vi } from "vitest";
import { renderHook, act, waitFor } from "@testing-library/react";
import { useMapColorThresholds } from "../useMapColorThresholds";
import * as api from "../../api/config";

vi.mock("../../api/config");

describe("useMapColorThresholds", () => {
  it("loads thresholds and exposes values", async () => {
    const mocked = vi.mocked(api.fetchMapColorThresholds);
    mocked.mockResolvedValue({ threshold_low: 10, threshold_medium: 20, threshold_high: 50 });

    const { result } = renderHook(() => useMapColorThresholds());

    expect(result.current.loading).toBe(true);
    await waitFor(() => {
      expect(result.current.loading).toBe(false);
    });
    expect(result.current.thresholds).toEqual({ threshold_low: 10, threshold_medium: 20, threshold_high: 50 });
    expect(result.current.error).toBeNull();
  });

  it("updates thresholds via callback", async () => {
    const fetchMock = vi.mocked(api.fetchMapColorThresholds);
    const updateMock = vi.mocked(api.updateMapColorThresholds);

    fetchMock.mockResolvedValue({ threshold_low: 10, threshold_medium: 20, threshold_high: 50 });
    updateMock.mockResolvedValue({ threshold_low: 15, threshold_medium: 25, threshold_high: 75 });

    const { result } = renderHook(() => useMapColorThresholds());
    await waitFor(() => {
      expect(result.current.loading).toBe(false);
    });

    await act(async () => {
      await result.current.updateThresholds({ threshold_low: 15, threshold_medium: 25, threshold_high: 75 });
    });

    expect(result.current.thresholds).toEqual({ threshold_low: 15, threshold_medium: 25, threshold_high: 75 });
  });
});
