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

import { api } from "./api";
import { I18nProvider } from "./i18n/I18nProvider";
import LandingPage from "./views/LandingPage";

const mockNavigate = jest.fn();
jest.mock("react-router-dom", () => ({
  ...jest.requireActual("react-router-dom"),
  useNavigate: () => mockNavigate,
}));

jest.mock("./api", () => ({ api: { get: jest.fn(), put: jest.fn().mockResolvedValue({ data: {} }) } }));

beforeEach(() => {
  jest.clearAllMocks();
  window.localStorage.clear();
  (api.get as jest.Mock).mockRejectedValue({ response: { status: 401 } });
});

test("shows exactly Free and Pro without invented commercial terms", async () => {
  render(
    <MemoryRouter>
      <I18nProvider><LandingPage /></I18nProvider>
    </MemoryRouter>,
  );

  expect(await screen.findByRole("heading", { name: "Two clear plans" })).toBeInTheDocument();
  expect(screen.getAllByRole("heading", { level: 3 }).map((heading) => heading.textContent)).toEqual(["Free", "Pro"]);
  expect(screen.queryByText(/bring your own key|unlimited AI|billed monthly|trial|£9|£3/i)).not.toBeInTheDocument();
  expect(screen.getByText(/Commercial terms appear only in configured checkout/i)).toBeInTheDocument();

  fireEvent.click(screen.getByRole("button", { name: "Create a Free account" }));
  expect(mockNavigate).toHaveBeenCalledWith("/register");

  fireEvent.click(screen.getByRole("button", { name: "Sign in to view Pro" }));
  expect(mockNavigate).toHaveBeenCalledWith("/login", { state: { from: "/settings" } });
});

test("switches the public landing page to Norwegian Bokmål", async () => {
  render(<MemoryRouter><I18nProvider><LandingPage /></I18nProvider></MemoryRouter>);

  fireEvent.click(await screen.findByRole("button", { name: "Norsk" }));
  expect(await screen.findByRole("heading", { name: "To tydelige alternativer" })).toBeInTheDocument();
  expect(screen.getByRole("button", { name: "Opprett en Free-konto" })).toBeInTheDocument();
});
