import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { vi } from "vitest";

const { navigate } = vi.hoisted(() => ({ navigate: vi.fn() }));

vi.mock("react-router-dom", async (importOriginal) => {
  const actual = await importOriginal<typeof import("react-router-dom")>();
  return { ...actual, useNavigate: () => navigate };
});
vi.mock("@/api/repairsCreate", () => ({
  searchCars: vi.fn().mockResolvedValue([]),
}));

import CarSelectPage from "@/pages/repairs/CarSelectPage";

beforeEach(() => navigate.mockClear());

test("«Машина не из парка» → ввод номера → navigate в external-режим со state (номер trim'ится)", async () => {
  const user = userEvent.setup();
  render(<CarSelectPage />);

  await user.click(screen.getByText("+ Машина не из парка"));
  await user.type(screen.getByPlaceholderText("Х999ХХ199"), " х999хх199 ");
  await user.type(screen.getByPlaceholderText("Toyota Camry"), "Toyota Camry");
  await user.click(screen.getByText("Продолжить →"));

  expect(navigate).toHaveBeenCalledWith("/repairs/new-external", {
    state: { plate: "х999хх199", make: "Toyota Camry" },
  });
});

test("марка опциональна → make=null если поле пустое", async () => {
  const user = userEvent.setup();
  render(<CarSelectPage />);

  await user.click(screen.getByText("+ Машина не из парка"));
  await user.type(screen.getByPlaceholderText("Х999ХХ199"), "А001АА125");
  await user.click(screen.getByText("Продолжить →"));

  expect(navigate).toHaveBeenCalledWith("/repairs/new-external", {
    state: { plate: "А001АА125", make: null },
  });
});

test("«Продолжить» заблокирована без номера", async () => {
  const user = userEvent.setup();
  render(<CarSelectPage />);
  await user.click(screen.getByText("+ Машина не из парка"));
  expect(screen.getByText("Продолжить →").closest("button")).toBeDisabled();
});
