import { act, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, expect, test, vi } from "vitest";

import { SearchToolbar } from "@/shared/ui/search-toolbar";

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

test("SearchToolbar keeps search controlled, renders filters, and emits only a debounced generic query", () => {
  vi.useFakeTimers();
  const onQueryChange = vi.fn();
  const onSearchChange = vi.fn();
  const { rerender } = render(
    <SearchToolbar
      filters={<select aria-label="상태 필터"><option>전체</option></select>}
      onQueryChange={onQueryChange}
      onSearchChange={onSearchChange}
      search=""
    />,
  );

  fireEvent.change(screen.getByRole("searchbox", { name: "검색어" }), { target: { value: "루나" } });

  expect(onSearchChange).toHaveBeenCalledWith("루나");
  expect(screen.getByLabelText("상태 필터")).toBeInTheDocument();
  expect(onQueryChange).not.toHaveBeenCalled();

  rerender(
    <SearchToolbar
      filters={<select aria-label="상태 필터"><option>전체</option></select>}
      onQueryChange={onQueryChange}
      onSearchChange={onSearchChange}
      search="루나"
    />,
  );
  act(() => vi.advanceTimersByTime(299));
  expect(onQueryChange).not.toHaveBeenCalled();

  act(() => vi.advanceTimersByTime(1));
  expect(onQueryChange).toHaveBeenCalledWith("루나");
});
