import React from "react";
import "@testing-library/jest-dom";
import { fireEvent, render, screen } from "@testing-library/react";

import { api } from "./api";
import { I18nProvider } from "./i18n/I18nProvider";
import { ToastProvider } from "./toast";
import AdminAuditPage from "./views/AdminAuditPage";

jest.mock("./api", () => ({
  api: { get: jest.fn(), post: jest.fn() },
  getApiErrorMessage: jest.fn((_error, fallback) => fallback),
}));

const mockedApi = api as jest.Mocked<typeof api>;

function renderPage() {
  return render(<ToastProvider><I18nProvider><AdminAuditPage /></I18nProvider></ToastProvider>);
}

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

test("distinguishes an unavailable audit log from an empty audit log and retries", async () => {
  mockedApi.get.mockRejectedValueOnce(new Error("offline"));
  renderPage();

  expect(await screen.findByText("Unable to load audit events")).toBeInTheDocument();
  expect(screen.queryByText("No events.")).not.toBeInTheDocument();

  mockedApi.get.mockResolvedValueOnce({ data: [] } as any);
  fireEvent.click(screen.getByRole("button", { name: "Retry" }));
  expect(await screen.findByText("No events.")).toBeInTheDocument();
});

test("localizes audit actions in Bokmål without translating stored event data", async () => {
  window.localStorage.setItem("uiLanguage", "nb-NO");
  mockedApi.get.mockResolvedValueOnce({ data: [{
    id: 7,
    type: "Deleted",
    at: "2026-08-29T12:00:00Z",
    jobApplicationId: 42,
    companyName: "Example AS",
    note: "User-authored note",
  }] } as any);

  renderPage();

  expect(await screen.findByRole("button", { name: "Angre" })).toBeInTheDocument();
  expect(screen.getByRole("button", { name: "Gjenopprett" })).toBeInTheDocument();
  expect(screen.getByText("Example AS - Jobb #42")).toBeInTheDocument();
  expect(screen.getByText("User-authored note")).toBeInTheDocument();
});
