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

import { api } from "./api";
import { setAuthUserKey } from "./auth";
import SavedViewsMenu from "./components/SavedViewsMenu";
import { useCompanies } from "./hooks/useCompanies";
import { I18nProvider } from "./i18n/I18nProvider";

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

function CompaniesProbe() {
  const { companies } = useCompanies();
  return <div>{companies.map((company) => company.name).join(", ") || "No companies"}</div>;
}

describe("account-scoped browser state", () => {
  beforeEach(() => {
    window.localStorage.clear();
    jest.clearAllMocks();
  });

  it("keeps saved views private to the account that created them", async () => {
    setAuthUserKey("user-a", false);
    const first = render(
      <I18nProvider>
        <SavedViewsMenu current={{ status: "Interview" }} onApply={jest.fn()} />
      </I18nProvider>,
    );

    fireEvent.click(screen.getByRole("button", { name: "Saved views" }));
    fireEvent.change(screen.getByLabelText("Name"), { target: { value: "User A interviews" } });
    fireEvent.click(screen.getByRole("button", { name: "Save current" }));
    expect(screen.getByText("User A interviews")).toBeInTheDocument();
    first.unmount();

    setAuthUserKey("user-b", false);
    render(
      <I18nProvider>
        <SavedViewsMenu current={{}} onApply={jest.fn()} />
      </I18nProvider>,
    );
    fireEvent.click(screen.getByRole("button", { name: "Saved views" }));

    expect(screen.queryByText("User A interviews")).not.toBeInTheDocument();
    expect(screen.getByText("No saved views yet.")).toBeInTheDocument();
  });

  it("does not show a previous account's cached companies after account switching", async () => {
    setAuthUserKey("user-a", false);
    mockedApi.get.mockResolvedValueOnce({ data: [{ id: 1, name: "User A Company" }] } as any);
    render(<CompaniesProbe />);
    expect(await screen.findByText("User A Company")).toBeInTheDocument();

    mockedApi.get.mockResolvedValueOnce({ data: [{ id: 2, name: "User B Company" }] } as any);
    setAuthUserKey("user-b", false);

    await waitFor(() => expect(screen.getByText("User B Company")).toBeInTheDocument());
    expect(screen.queryByText("User A Company")).not.toBeInTheDocument();
  });
});
