/**
 * @vitest-environment jsdom
 */
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { UserSearchBar } from "./user-search-bar";

vi.mock("react-i18next", () => ({
  useTranslation: () => ({
    t: (_key: string, fallback: string): string => fallback,
  }),
}));

afterEach(() => {
  cleanup();
});

describe("UserSearchBar", () => {
  it("keeps the controls usable on a narrow mobile viewport", () => {
    Object.defineProperty(window, "innerWidth", {
      configurable: true,
      value: 390,
    });

    render(
      <UserSearchBar
        initialType="email"
        initialValue=""
        onSearch={vi.fn()}
        subscribes={[]}
      />
    );

    expect(screen.getByRole("combobox")).not.toBeNull();
    expect(screen.getByRole("button", { name: "Search" })).not.toBeNull();
  });

  it("keeps the typed happy-path value and triggers search", () => {
    const onSearch = vi.fn();

    render(
      <UserSearchBar
        initialType="email"
        initialValue=""
        onSearch={onSearch}
        subscribes={[]}
      />
    );

    fireEvent.change(screen.getByPlaceholderText("Enter search term"), {
      target: { value: "user@example.com" },
    });
    fireEvent.click(screen.getByRole("button", { name: "Search" }));

    expect(onSearch).toHaveBeenCalledWith("email", "user@example.com");
    expect(
      (screen.getByPlaceholderText("Enter search term") as HTMLInputElement)
        .value
    ).toBe("user@example.com");
  });

  it("syncs to external search changes for precise referrer navigation", () => {
    const onSearch = vi.fn();
    const { rerender } = render(
      <UserSearchBar
        initialType="email"
        initialValue="old@example.com"
        onSearch={onSearch}
        subscribes={[]}
      />
    );

    expect(
      (screen.getByPlaceholderText("Enter search term") as HTMLInputElement)
        .value
    ).toBe("old@example.com");

    rerender(
      <UserSearchBar
        initialType="user_id"
        initialValue="1024"
        onSearch={onSearch}
        subscribes={[]}
      />
    );

    expect(
      (screen.getByPlaceholderText("Enter search term") as HTMLInputElement)
        .value
    ).toBe("1024");
  });
});
