import { describe, it, expect } from "vitest";
import { renderHook, act } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { useTabRouter } from "../useTabRouter";

describe("useTabRouter", () => {
  it("initializes with jails tab selected by default", () => {
    const { result } = renderHook(() => useTabRouter(), {
      wrapper: ({ children }) => <MemoryRouter>{children}</MemoryRouter>,
    });

    expect(result.current.activeTab).toBe("jails");
    expect(result.current.activeItem).toBeNull();
  });

  it("selects a new tab", () => {
    const { result } = renderHook(() => useTabRouter(), {
      wrapper: ({ children }) => <MemoryRouter>{children}</MemoryRouter>,
    });

    act(() => {
      result.current.selectTab("filters");
    });

    expect(result.current.activeTab).toBe("filters");
  });

  it("clears active item when selecting a new tab", () => {
    const { result } = renderHook(() => useTabRouter(), {
      wrapper: ({ children }) => <MemoryRouter>{children}</MemoryRouter>,
    });

    act(() => {
      result.current.selectTabWithItem("jails", "test-jail");
    });

    expect(result.current.activeItem).toBe("test-jail");

    act(() => {
      result.current.selectTab("filters");
    });

    expect(result.current.activeItem).toBeNull();
  });

  it("selects a tab with an active item", () => {
    const { result } = renderHook(() => useTabRouter(), {
      wrapper: ({ children }) => <MemoryRouter>{children}</MemoryRouter>,
    });

    act(() => {
      result.current.selectTabWithItem("jails", "sshd");
    });

    expect(result.current.activeTab).toBe("jails");
    expect(result.current.activeItem).toBe("sshd");
  });

  it("supports all valid tab IDs", () => {
    const { result } = renderHook(() => useTabRouter(), {
      wrapper: ({ children }) => <MemoryRouter>{children}</MemoryRouter>,
    });

    const tabs = ["jails", "filters", "actions", "server", "regex"] as const;

    tabs.forEach((tab) => {
      act(() => {
        result.current.selectTab(tab);
      });
      expect(result.current.activeTab).toBe(tab);
    });
  });

  it("clears active item when setting item to null", () => {
    const { result } = renderHook(() => useTabRouter(), {
      wrapper: ({ children }) => <MemoryRouter>{children}</MemoryRouter>,
    });

    act(() => {
      result.current.selectTabWithItem("jails", "sshd");
    });

    expect(result.current.activeItem).toBe("sshd");

    act(() => {
      result.current.selectTabWithItem("jails", null);
    });

    expect(result.current.activeItem).toBeNull();
  });
});
