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 { I18nProvider } from "./i18n/I18nProvider";
import JobDiscoveryPage from "./views/JobDiscoveryPage";

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

function renderPage() {
  return render(<I18nProvider><MemoryRouter><JobDiscoveryPage /></MemoryRouter></I18nProvider>);
}

beforeEach(() => window.localStorage.clear());
afterEach(() => jest.clearAllMocks());

test("shows honest source metadata and offers the existing reviewed save flow", async () => {
  mockedApi.get.mockResolvedValue({ data: [{ id: "abc", title: "Backend Developer", company: "Acme", location: "OSLO", modifiedAt: "2026-08-01T10:00:00Z", deadline: "2026-08-15T23:59:59Z", url: "https://arbeidsplassen.nav.no/stillinger/stilling/abc", source: "nav", sourceName: "NAV Arbeidsplassen", acquisitionType: "searched", retrievedAt: "2026-08-10T10:00:00Z", countryCode: "NO" }] } as any);
  renderPage();

  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();
  expect(screen.getByText("NAV Arbeidsplassen")).toBeInTheDocument();
  expect(screen.getByText(/Searched listing · Retrieved/)).toBeInTheDocument();
  expect(screen.getByText(/Application deadline:/)).toBeInTheDocument();
  await waitFor(() => expect(mockedApi.get).toHaveBeenCalledWith("/job-discovery/search", { params: { q: "backend", location: undefined } }));
  expect(screen.getByRole("button", { name: "Save to tracker" })).toBeInTheDocument();
});

test("distinguishes the initial guidance from a completed empty search", async () => {
  mockedApi.get.mockResolvedValue({ data: [] } as any);
  renderPage();

  expect(screen.getByText("Search recent active vacancies by role, company, or municipality.")).toBeInTheDocument();
  fireEvent.click(screen.getByRole("button", { name: "Search NAV" }));

  expect(await screen.findByText(/No active vacancies matched this search/)).toBeInTheDocument();
  expect(screen.queryByText("Search recent active vacancies by role, company, or municipality.")).not.toBeInTheDocument();
});

test("retries the last submitted search after an error", async () => {
  mockedApi.get.mockRejectedValueOnce(new Error("offline")).mockResolvedValueOnce({ data: [] } as any);
  renderPage();

  fireEvent.change(screen.getByLabelText("Role or company"), { target: { value: "  utvikler  " } });
  fireEvent.change(screen.getByLabelText("Municipality"), { target: { value: "  Oslo  " } });
  fireEvent.click(screen.getByRole("button", { name: "Search NAV" }));
  fireEvent.click(await screen.findByRole("button", { name: "Retry" }));

  await waitFor(() => expect(mockedApi.get).toHaveBeenCalledTimes(2));
  expect(mockedApi.get).toHaveBeenLastCalledWith("/job-discovery/search", { params: { q: "utvikler", location: "Oslo" } });
});

test("sorts returned vacancies by title", async () => {
  mockedApi.get.mockResolvedValue({ data: [
    { id: "2", title: "Zoologist", url: "https://arbeidsplassen.nav.no/2", source: "nav", countryCode: "NO" },
    { id: "1", title: "Analyst", url: "https://arbeidsplassen.nav.no/1", source: "nav", countryCode: "NO" },
  ] } as any);
  renderPage();
  fireEvent.click(screen.getByRole("button", { name: "Search NAV" }));
  await screen.findByText("2 vacancies found");

  fireEvent.mouseDown(screen.getByRole("combobox", { name: "Sort results" }));
  fireEvent.click(await screen.findByRole("option", { name: "Title A–Z" }));

  const titles = screen.getAllByRole("heading", { level: 6 }).map((element) => element.textContent);
  expect(titles).toEqual(["Analyst", "Zoologist"]);
});

test("renders the discovery workflow in Norwegian Bokmål", async () => {
  window.localStorage.setItem("uiLanguage", "nb");
  mockedApi.get.mockResolvedValue({ data: [] } as any);
  renderPage();

  expect(screen.getByLabelText("Rolle eller bedrift")).toBeInTheDocument();
  fireEvent.click(screen.getByRole("button", { name: "Søk i NAV" }));
  expect(await screen.findByText(/Ingen aktive stillinger samsvarte/)).toBeInTheDocument();
});
