import React from "react";
import "@testing-library/jest-dom";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { api } from "./api";
import JobDiscoveryPage from "./views/JobDiscoveryPage";

jest.mock("./api", () => ({ api: { get: jest.fn() } }));
const mockedApi = api as jest.Mocked<typeof api>;

test("searches NAV and offers the existing reviewed save flow", async () => {
  mockedApi.get.mockResolvedValue({ data: [{ id: "abc", title: "Backend Developer", company: "Acme", location: "OSLO", url: "https://arbeidsplassen.nav.no/stillinger/stilling/abc", source: "nav", countryCode: "NO" }] } as any);
  render(<MemoryRouter future={{ v7_startTransition: true, v7_relativeSplatPath: true }}><JobDiscoveryPage /></MemoryRouter>);

  fireEvent.change(screen.getByLabelText("Role or company"), { target: { value: "backend" } });
  fireEvent.click(screen.getByRole("button", { name: "Search NAV" }));

  expect(await screen.findByText("Backend Developer")).toBeInTheDocument();
  await waitFor(() => expect(mockedApi.get).toHaveBeenCalledWith("/job-discovery/search", { params: { q: "backend", location: undefined } }));
  expect(screen.getByRole("button", { name: "Save to tracker" })).toBeInTheDocument();
});
