import { describe, expect, it, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { FluentProvider, webLightTheme } from "@fluentui/react-components";
import { HistoryPage } from "../HistoryPage";

let lastQuery: Record<string, unknown> | null = null;
const mockUseHistory = vi.fn((query: Record<string, unknown>) => {
  lastQuery = query;
  return {
    items: [],
    total: 0,
    page: 1,
    loading: false,
    error: null,
    setPage: vi.fn(),
    refresh: vi.fn(),
  };
});

vi.mock("../hooks/useHistory", () => ({
  useHistory: (query: Record<string, unknown>) => mockUseHistory(query),
  useIpHistory: () => ({ detail: null, loading: false, error: null, refresh: vi.fn() }),
}));

vi.mock("../components/WorldMap", () => ({
  WorldMap: () => <div data-testid="world-map" />,
}));

vi.mock("../api/config", () => ({
  fetchMapColorThresholds: async () => ({
    threshold_low: 10,
    threshold_medium: 50,
    threshold_high: 100,
  }),
}));

describe("HistoryPage", () => {
  it("renders DashboardFilterBar and applies origin+range filters", async () => {
    const user = userEvent.setup();

    render(
      <FluentProvider theme={webLightTheme}>
        <HistoryPage />
      </FluentProvider>,
    );

    // Initial load should include the default query.
    expect(lastQuery).toEqual({ page_size: 50 });

    // Change the time-range and origin filter, then apply.
    await user.click(screen.getByRole("button", { name: /Last 7 days/i }));
    await user.click(screen.getByRole("button", { name: /Blocklist/i }));
    await user.click(screen.getByRole("button", { name: /Apply/i }));

    expect(lastQuery).toMatchObject({ range: "7d", origin: "blocklist" });
  });
});
