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

import { api } from "./api";
import AiSectionAssistant from "./components/cv/AiSectionAssistant";
import { I18nProvider } from "./i18n/I18nProvider";
import { ToastProvider } from "./toast";

jest.mock("./accountPlan", () => ({ useAccountPlan: () => ({ canUseAi: true }) }));
jest.mock("./api", () => ({
  api: {
    get: jest.fn(), post: jest.fn(), put: jest.fn(), delete: jest.fn(),
    interceptors: { request: { use: jest.fn() }, response: { use: jest.fn() } },
  },
  getApiErrorMessage: (_error: unknown, fallback?: string) => fallback ?? "Request failed.",
}));

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

function renderAssistant(onApply = jest.fn()) {
  render(
    <I18nProvider>
      <ToastProvider>
        <AiSectionAssistant
          sectionName="Erfaring"
          text="Built reliable APIs"
          documentLanguage="nb-NO"
          onApply={onApply}
        />
      </ToastProvider>
    </I18nProvider>,
  );
  return onApply;
}

beforeEach(() => {
  window.localStorage.removeItem("uiLanguage");
  jest.clearAllMocks();
});

afterEach(() => window.localStorage.removeItem("uiLanguage"));

test("section AI uses the CV document language and requires explicit apply", async () => {
  mockedApi.post.mockResolvedValue({ data: { original: "Built reliable APIs", result: "Utviklet driftssikre API-er" } } as never);
  const onApply = renderAssistant();

  fireEvent.click(screen.getByRole("button", { name: "AI suggestions" }));
  expect(screen.getByLabelText("Output language")).toHaveTextContent("Norsk bokmål");
  fireEvent.click(screen.getByRole("button", { name: "Suggest" }));

  await waitFor(() => expect(mockedApi.post).toHaveBeenCalledWith("/cv/ai/assist", expect.objectContaining({
    action: "improve",
    language: "nb-NO",
    text: "Built reliable APIs",
  })));
  expect(onApply).not.toHaveBeenCalled();
  expect(await screen.findByDisplayValue("Utviklet driftssikre API-er")).toBeInTheDocument();
  fireEvent.click(screen.getByRole("button", { name: "Apply" }));
  expect(onApply).toHaveBeenCalledWith("Utviklet driftssikre API-er");
});

test("section AI controls render in Bokmål without changing the document language", () => {
  window.localStorage.setItem("uiLanguage", "nb");
  renderAssistant();

  fireEvent.click(screen.getByRole("button", { name: "AI-forslag" }));
  expect(screen.getByLabelText("AI-handling")).toBeInTheDocument();
  expect(screen.getByLabelText("Språk for resultat")).toHaveTextContent("Norsk bokmål");
  expect(screen.getByRole("button", { name: "Foreslå" })).toBeInTheDocument();
});
