import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";

import { SkipLink } from "../SkipLink";

const TestBase = ({ skipProps }) => (
  <html>
    <head>
      <meta httpEquiv="Content-Type" content="text/html; charset=utf-8" />
      <meta httpEquiv="X-UA-Compatible" content="IE=edge, chrome=1" />
      <meta
        name="viewport"
        content="width=device-width, initial-scale=1.0, user-scalable=yes"
      />
    </head>
    <body>
      <div id="root">
        <SkipLink data-testid="skip-link" {...skipProps} />
        <nav>
          <a href="/">Home</a>
        </nav>
        <main tabIndex={-1} id="maincontent" data-testid="maincontent">
          <h1>Heading</h1>
          <a href="/" data-testid="mainlink">
            Link
          </a>
        </main>
      </div>
      <div id="root-modals" />
      <div id="root-dropdowns" />
      <div id="root-tooltips" />
    </body>
  </html>
);

//children were required plus they helped to check defaultTabIndex
describe("rendering", () => {
  describe("initial state", () => {
    it("rendered", () => {
      const { getByTestId } = render(<TestBase />);
      expect(getByTestId("skip-link")).toBeInTheDocument();
    });
    it("has class skip-link", () => {
      const { getByTestId } = render(<TestBase />);
      expect(getByTestId("skip-link")).toHaveClass("skip-link");
    });
    it("has href #maincontent", () => {
      const { getByTestId } = render(<TestBase />);
      expect(getByTestId("skip-link").getAttribute("href")).toBe(
        "#maincontent",
      );
    });
  });
  describe("passed props", () => {
    it("has additional class when className is set", () => {
      const { getByTestId } = render(
        <TestBase skipProps={{ className: "test-class" }} />,
      );
      expect(getByTestId("skip-link")).toHaveClass("skip-link");
      expect(getByTestId("skip-link")).toHaveClass("test-class");
    });
  });
});

describe("keyboard navigation", () => {
  it("focuses on first tab", async () => {
    render(<TestBase />);

    const { tab } = userEvent.setup();
    await tab();

    expect(screen.getByTestId("skip-link")).toHaveFocus();
  });

  it.fails("focuses main on click", async () => {
    render(<TestBase />);

    const { tab, keyboard } = userEvent.setup();
    await tab();
    await keyboard("{Enter}");

    expect(screen.getByTestId("maincontent")).toHaveFocus();
  });
});
